Merge pull request #1412 from esdrubal/stackframe
[mono.git] / mono / utils / strtod.c
1 /****************************************************************
2  *
3  * The author of this software is David M. Gay.
4  *
5  * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose without fee is hereby granted, provided that this entire notice
9  * is included in all copies of any software which is or includes a copy
10  * or modification of this software and in all copies of the supporting
11  * documentation for such software.
12  *
13  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
14  * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
15  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
16  * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
17  *
18  ***************************************************************/
19 #include "config.h"
20 #include "strtod.h"
21 #include <glib.h>
22 #define freedtoa __freedtoa
23 #define dtoa __dtoa
24
25 #define Omit_Private_Memory
26 #define MULTIPLE_THREADS 1
27 /* Lock 0 is not used because of USE_MALLOC, Lock 1 protects a lazy-initialized table */
28 #define ACQUIRE_DTOA_LOCK(n)
29 #define FREE_DTOA_LOCK(n)
30
31 /* Please send bug reports to David M. Gay (dmg at acm dot org,
32  * with " at " changed at "@" and " dot " changed to ".").      */
33
34 /* On a machine with IEEE extended-precision registers, it is
35  * necessary to specify double-precision (53-bit) rounding precision
36  * before invoking strtod or dtoa.  If the machine uses (the equivalent
37  * of) Intel 80x87 arithmetic, the call
38  *      _control87(PC_53, MCW_PC);
39  * does this with many compilers.  Whether this or another call is
40  * appropriate depends on the compiler; for this to work, it may be
41  * necessary to #include "float.h" or another system-dependent header
42  * file.
43  */
44
45 /* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
46  *
47  * This strtod returns a nearest machine number to the input decimal
48  * string (or sets errno to ERANGE).  With IEEE arithmetic, ties are
49  * broken by the IEEE round-even rule.  Otherwise ties are broken by
50  * biased rounding (add half and chop).
51  *
52  * Inspired loosely by William D. Clinger's paper "How to Read Floating
53  * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
54  *
55  * Modifications:
56  *
57  *      1. We only require IEEE, IBM, or VAX double-precision
58  *              arithmetic (not IEEE double-extended).
59  *      2. We get by with floating-point arithmetic in a case that
60  *              Clinger missed -- when we're computing d * 10^n
61  *              for a small integer d and the integer n is not too
62  *              much larger than 22 (the maximum integer k for which
63  *              we can represent 10^k exactly), we may be able to
64  *              compute (d*10^k) * 10^(e-k) with just one roundoff.
65  *      3. Rather than a bit-at-a-time adjustment of the binary
66  *              result in the hard case, we use floating-point
67  *              arithmetic to determine the adjustment to within
68  *              one bit; only in really hard cases do we need to
69  *              compute a second residual.
70  *      4. Because of 3., we don't need a large table of powers of 10
71  *              for ten-to-e (just some small tables, e.g. of 10^k
72  *              for 0 <= k <= 22).
73  */
74
75 /*
76  * #define IEEE_8087 for IEEE-arithmetic machines where the least
77  *      significant byte has the lowest address.
78  * #define IEEE_MC68k for IEEE-arithmetic machines where the most
79  *      significant byte has the lowest address.
80  * #define Long int on machines with 32-bit ints and 64-bit longs.
81  * #define IBM for IBM mainframe-style floating-point arithmetic.
82  * #define VAX for VAX-style floating-point arithmetic (D_floating).
83  * #define No_leftright to omit left-right logic in fast floating-point
84  *      computation of dtoa.
85  * #define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
86  *      and strtod and dtoa should round accordingly.
87  * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
88  *      and Honor_FLT_ROUNDS is not #defined.
89  * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
90  *      that use extended-precision instructions to compute rounded
91  *      products and quotients) with IBM.
92  * #define ROUND_BIASED for IEEE-format with biased rounding.
93  * #define Inaccurate_Divide for IEEE-format with correctly rounded
94  *      products but inaccurate quotients, e.g., for Intel i860.
95  * #define NO_LONG_LONG on machines that do not have a "long long"
96  *      integer type (of >= 64 bits).  On such machines, you can
97  *      #define Just_16 to store 16 bits per 32-bit Long when doing
98  *      high-precision integer arithmetic.  Whether this speeds things
99  *      up or slows things down depends on the machine and the number
100  *      being converted.  If long long is available and the name is
101  *      something other than "long long", #define Llong to be the name,
102  *      and if "unsigned Llong" does not work as an unsigned version of
103  *      Llong, #define #ULLong to be the corresponding unsigned type.
104  * #define KR_headers for old-style C function headers.
105  * #define Bad_float_h if your system lacks a float.h or if it does not
106  *      define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
107  *      FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
108  * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
109  *      if memory is available and otherwise does something you deem
110  *      appropriate.  If MALLOC is undefined, malloc will be invoked
111  *      directly -- and assumed always to succeed.
112  * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
113  *      memory allocations from a private pool of memory when possible.
114  *      When used, the private pool is PRIVATE_MEM bytes long:  2304 bytes,
115  *      unless #defined to be a different length.  This default length
116  *      suffices to get rid of MALLOC calls except for unusual cases,
117  *      such as decimal-to-binary conversion of a very long string of
118  *      digits.  The longest string dtoa can return is about 751 bytes
119  *      long.  For conversions by strtod of strings of 800 digits and
120  *      all dtoa conversions in single-threaded executions with 8-byte
121  *      pointers, PRIVATE_MEM >= 7400 appears to suffice; with 4-byte
122  *      pointers, PRIVATE_MEM >= 7112 appears adequate.
123  * #define INFNAN_CHECK on IEEE systems to cause strtod to check for
124  *      Infinity and NaN (case insensitively).  On some systems (e.g.,
125  *      some HP systems), it may be necessary to #define NAN_WORD0
126  *      appropriately -- to the most significant word of a quiet NaN.
127  *      (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
128  *      When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
129  *      strtod also accepts (case insensitively) strings of the form
130  *      NaN(x), where x is a string of hexadecimal digits and spaces;
131  *      if there is only one string of hexadecimal digits, it is taken
132  *      for the 52 fraction bits of the resulting NaN; if there are two
133  *      or more strings of hex digits, the first is for the high 20 bits,
134  *      the second and subsequent for the low 32 bits, with intervening
135  *      white space ignored; but if this results in none of the 52
136  *      fraction bits being on (an IEEE Infinity symbol), then NAN_WORD0
137  *      and NAN_WORD1 are used instead.
138  * #define MULTIPLE_THREADS if the system offers preemptively scheduled
139  *      multiple threads.  In this case, you must provide (or suitably
140  *      #define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
141  *      by FREE_DTOA_LOCK(n) for n = 0 or 1.  (The second lock, accessed
142  *      in pow5mult, ensures lazy evaluation of only one copy of high
143  *      powers of 5; omitting this lock would introduce a small
144  *      probability of wasting memory, but would otherwise be harmless.)
145  *      You must also invoke freedtoa(s) to free the value s returned by
146  *      dtoa.  You may do so whether or not MULTIPLE_THREADS is #defined.
147  * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
148  *      avoids underflows on inputs whose result does not underflow.
149  *      If you #define NO_IEEE_Scale on a machine that uses IEEE-format
150  *      floating-point numbers and flushes underflows to zero rather
151  *      than implementing gradual underflow, then you must also #define
152  *      Sudden_Underflow.
153  * #define YES_ALIAS to permit aliasing certain double values with
154  *      arrays of ULongs.  This leads to slightly better code with
155  *      some compilers and was always used prior to 19990916, but it
156  *      is not strictly legal and can cause trouble with aggressively
157  *      optimizing compilers (e.g., gcc 2.95.1 under -O2).
158  * #define USE_LOCALE to use the current locale's decimal_point value.
159  * #define SET_INEXACT if IEEE arithmetic is being used and extra
160  *      computation should be done to set the inexact flag when the
161  *      result is inexact and avoid setting inexact when the result
162  *      is exact.  In this case, dtoa.c must be compiled in
163  *      an environment, perhaps provided by #include "dtoa.c" in a
164  *      suitable wrapper, that defines two functions,
165  *              int get_inexact(void);
166  *              void clear_inexact(void);
167  *      such that get_inexact() returns a nonzero value if the
168  *      inexact bit is already set, and clear_inexact() sets the
169  *      inexact bit to 0.  When SET_INEXACT is #defined, strtod
170  *      also does extra computations to set the underflow and overflow
171  *      flags when appropriate (i.e., when the result is tiny and
172  *      inexact or when it is a numeric value rounded to +-infinity).
173  * #define NO_ERRNO if strtod should not assign errno = ERANGE when
174  *      the result overflows to +-Infinity or underflows to 0.
175  */
176 #if defined __BIG_ENDIAN__ || defined _BIG_ENDIAN
177 #   define IEEE_MC68k
178 #elif defined __LITTLE_ENDIAN__ || defined _LITTLE_ENDIAN
179 #   define IEEE_8087
180 #else
181
182 #if defined(TARGET_X86) || defined(mips) && defined(MIPSEL) || defined (__arm__) || defined(__aarch64__)
183
184 #   define IEEE_8087
185
186 #elif defined(TARGET_AMD64) || defined(__alpha__)
187
188 #   define IEEE_8087
189
190 #elif defined(__ia64)
191
192 #   ifdef __hpux
193 #       define IEEE_MC68k
194 #   else
195 #       define IEEE_8087
196 #   endif
197
198 #elif defined(__hppa)
199
200 #   define IEEE_MC68k
201
202 #else
203 #warning byte order unknown, assuming big endian
204 #define IEEE_MC68k
205 #endif
206
207 #endif
208
209 #define Long gint32
210 #define ULong guint32
211
212 #ifdef DEBUG
213 #include "stdio.h"
214 #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
215 #endif
216
217 #include "stdlib.h"
218 #include "string.h"
219
220 #undef USE_LOCALE
221 #ifdef USE_LOCALE
222 #include "locale.h"
223 #endif
224
225 #ifdef MALLOC
226 #ifdef KR_headers
227 extern char *MALLOC();
228 #else
229 extern void *MALLOC(size_t);
230 #endif
231 #else
232 #define MALLOC malloc
233 #endif
234
235 #define Omit_Private_Memory
236 #ifndef Omit_Private_Memory
237 #ifndef PRIVATE_MEM
238 #define PRIVATE_MEM 2304
239 #endif
240 #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
241 static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
242 #endif
243
244 #undef IEEE_Arith
245 #undef Avoid_Underflow
246 #ifdef IEEE_MC68k
247 #define IEEE_Arith
248 #endif
249 #ifdef IEEE_8087
250 #define IEEE_Arith
251 #endif
252
253 #include "errno.h"
254
255 #ifdef Bad_float_h
256
257 #ifdef IEEE_Arith
258 #define DBL_DIG 15
259 #define DBL_MAX_10_EXP 308
260 #define DBL_MAX_EXP 1024
261 #define FLT_RADIX 2
262 #endif /*IEEE_Arith*/
263
264 #ifdef IBM
265 #define DBL_DIG 16
266 #define DBL_MAX_10_EXP 75
267 #define DBL_MAX_EXP 63
268 #define FLT_RADIX 16
269 #define DBL_MAX 7.2370055773322621e+75
270 #endif
271
272 #ifdef VAX
273 #define DBL_DIG 16
274 #define DBL_MAX_10_EXP 38
275 #define DBL_MAX_EXP 127
276 #define FLT_RADIX 2
277 #define DBL_MAX 1.7014118346046923e+38
278 #endif
279
280 #ifndef LONG_MAX
281 #define LONG_MAX 2147483647
282 #endif
283
284 #else /* ifndef Bad_float_h */
285 #include "float.h"
286 #endif /* Bad_float_h */
287
288 #ifndef __MATH_H__
289 #include "math.h"
290 #endif
291
292 #ifdef __cplusplus
293 extern "C" {
294 #endif
295
296 #ifndef CONST
297 #ifdef KR_headers
298 #define CONST /* blank */
299 #else
300 #define CONST const
301 #endif
302 #endif
303
304 #if defined(IEEE_8087) + defined(IEEE_MC68k) + defined(VAX) + defined(IBM) != 1
305 Exactly one of IEEE_8087, IEEE_MC68k, VAX, or IBM should be defined.
306 #endif
307
308 typedef union { double d; ULong L[2]; } U;
309
310 #ifdef YES_ALIAS
311 #define dval(x) x
312 #ifdef IEEE_8087
313 #define word0(x) ((ULong *)&x)[1]
314 #define word1(x) ((ULong *)&x)[0]
315 #else
316 #define word0(x) ((ULong *)&x)[0]
317 #define word1(x) ((ULong *)&x)[1]
318 #endif
319 #else
320 #ifdef IEEE_8087
321 #define word0(x) ((U*)&x)->L[1]
322 #define word1(x) ((U*)&x)->L[0]
323 #else
324 #define word0(x) ((U*)&x)->L[0]
325 #define word1(x) ((U*)&x)->L[1]
326 #endif
327 #define dval(x) ((U*)&x)->d
328 #endif
329
330 /* The following definition of Storeinc is appropriate for MIPS processors.
331  * An alternative that might be better on some machines is
332  * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
333  */
334 #if defined(IEEE_8087) + defined(VAX)
335 #define Storeinc(a,b,c) do { (((unsigned short *)a)[1] = (unsigned short)b, \
336 ((unsigned short *)a)[0] = (unsigned short)c, a++) } while (0)
337 #else
338 #define Storeinc(a,b,c) do { (((unsigned short *)a)[0] = (unsigned short)b, \
339 ((unsigned short *)a)[1] = (unsigned short)c, a++) } while (0)
340 #endif
341
342 /* #define P DBL_MANT_DIG */
343 /* Ten_pmax = floor(P*log(2)/log(5)) */
344 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
345 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
346 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
347
348 #ifdef IEEE_Arith
349 #define Exp_shift  20
350 #define Exp_shift1 20
351 #define Exp_msk1    0x100000
352 #define Exp_msk11   0x100000
353 #define Exp_mask  0x7ff00000
354 #define P 53
355 #define Bias 1023
356 #define Emin (-1022)
357 #define Exp_1  0x3ff00000
358 #define Exp_11 0x3ff00000
359 #define Ebits 11
360 #define Frac_mask  0xfffff
361 #define Frac_mask1 0xfffff
362 #define Ten_pmax 22
363 #define Bletch 0x10
364 #define Bndry_mask  0xfffff
365 #define Bndry_mask1 0xfffff
366 #define LSB 1
367 #define Sign_bit 0x80000000
368 #define Log2P 1
369 #define Tiny0 0
370 #define Tiny1 1
371 #define Quick_max 14
372 #define Int_max 14
373 #ifndef NO_IEEE_Scale
374 #define Avoid_Underflow
375 #ifdef Flush_Denorm     /* debugging option */
376 #undef Sudden_Underflow
377 #endif
378 #endif
379
380 #ifndef Flt_Rounds
381 #ifdef FLT_ROUNDS
382 #define Flt_Rounds FLT_ROUNDS
383 #else
384 #define Flt_Rounds 1
385 #endif
386 #endif /*Flt_Rounds*/
387
388 #ifdef Honor_FLT_ROUNDS
389 #define Rounding rounding
390 #undef Check_FLT_ROUNDS
391 #define Check_FLT_ROUNDS
392 #else
393 #define Rounding Flt_Rounds
394 #endif
395
396 #else /* ifndef IEEE_Arith */
397 #undef Check_FLT_ROUNDS
398 #undef Honor_FLT_ROUNDS
399 #undef SET_INEXACT
400 #undef  Sudden_Underflow
401 #define Sudden_Underflow
402 #ifdef IBM
403 #undef Flt_Rounds
404 #define Flt_Rounds 0
405 #define Exp_shift  24
406 #define Exp_shift1 24
407 #define Exp_msk1   0x1000000
408 #define Exp_msk11  0x1000000
409 #define Exp_mask  0x7f000000
410 #define P 14
411 #define Bias 65
412 #define Exp_1  0x41000000
413 #define Exp_11 0x41000000
414 #define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
415 #define Frac_mask  0xffffff
416 #define Frac_mask1 0xffffff
417 #define Bletch 4
418 #define Ten_pmax 22
419 #define Bndry_mask  0xefffff
420 #define Bndry_mask1 0xffffff
421 #define LSB 1
422 #define Sign_bit 0x80000000
423 #define Log2P 4
424 #define Tiny0 0x100000
425 #define Tiny1 0
426 #define Quick_max 14
427 #define Int_max 15
428 #else /* VAX */
429 #undef Flt_Rounds
430 #define Flt_Rounds 1
431 #define Exp_shift  23
432 #define Exp_shift1 7
433 #define Exp_msk1    0x80
434 #define Exp_msk11   0x800000
435 #define Exp_mask  0x7f80
436 #define P 56
437 #define Bias 129
438 #define Exp_1  0x40800000
439 #define Exp_11 0x4080
440 #define Ebits 8
441 #define Frac_mask  0x7fffff
442 #define Frac_mask1 0xffff007f
443 #define Ten_pmax 24
444 #define Bletch 2
445 #define Bndry_mask  0xffff007f
446 #define Bndry_mask1 0xffff007f
447 #define LSB 0x10000
448 #define Sign_bit 0x8000
449 #define Log2P 1
450 #define Tiny0 0x80
451 #define Tiny1 0
452 #define Quick_max 15
453 #define Int_max 15
454 #endif /* IBM, VAX */
455 #endif /* IEEE_Arith */
456
457 #ifndef IEEE_Arith
458 #define ROUND_BIASED
459 #endif
460
461 #ifdef RND_PRODQUOT
462 #define rounded_product(a,b) a = rnd_prod(a, b)
463 #define rounded_quotient(a,b) a = rnd_quot(a, b)
464 #ifdef KR_headers
465 extern double rnd_prod(), rnd_quot();
466 #else
467 extern double rnd_prod(double, double), rnd_quot(double, double);
468 #endif
469 #else
470 #define rounded_product(a,b) a *= b
471 #define rounded_quotient(a,b) a /= b
472 #endif
473
474 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
475 #define Big1 0xffffffff
476
477 #ifndef Pack_32
478 #define Pack_32
479 #endif
480
481 #ifdef KR_headers
482 #define FFFFFFFF ((((unsigned long)0xffff)<<16)|(unsigned long)0xffff)
483 #else
484 #define FFFFFFFF 0xffffffffUL
485 #endif
486
487 #ifdef NO_LONG_LONG
488 #undef ULLong
489 #ifdef Just_16
490 #undef Pack_32
491 /* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
492  * This makes some inner loops simpler and sometimes saves work
493  * during multiplications, but it often seems to make things slightly
494  * slower.  Hence the default is now to store 32 bits per Long.
495  */
496 #endif
497 #else   /* long long available */
498 #ifndef Llong
499 #define Llong long long
500 #endif
501 #ifndef ULLong
502 #define ULLong unsigned Llong
503 #endif
504 #endif /* NO_LONG_LONG */
505
506 #ifndef MULTIPLE_THREADS
507 #define ACQUIRE_DTOA_LOCK(n)    /*nothing*/
508 #define FREE_DTOA_LOCK(n)       /*nothing*/
509 #endif
510
511 #define Kmax 15
512
513 #ifdef __cplusplus
514 extern "C" double strtod(const char *s00, char **se);
515 extern "C" char *dtoa(double d, int mode, int ndigits,
516                         int *decpt, int *sign, char **rve);
517 #endif
518
519  struct
520 Bigint {
521         struct Bigint *next;
522         int k, maxwds, sign, wds;
523         ULong x[1];
524         };
525
526  typedef struct Bigint Bigint;
527
528  static Bigint *freelist[Kmax+1];
529
530  static Bigint *
531 Balloc
532 #ifdef KR_headers
533         (k) int k;
534 #else
535         (int k)
536 #endif
537 {
538         int x;
539         Bigint *rv;
540 #ifndef Omit_Private_Memory
541         unsigned int len;
542 #endif
543
544         ACQUIRE_DTOA_LOCK(0);
545         if ((rv = freelist[k])) {
546                 freelist[k] = rv->next;
547                 }
548         else {
549                 x = 1 << k;
550 #ifdef Omit_Private_Memory
551                 rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
552 #else
553                 len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
554                         /sizeof(double);
555                 if (pmem_next - private_mem + len <= PRIVATE_mem) {
556                         rv = (Bigint*)pmem_next;
557                         pmem_next += len;
558                         }
559                 else
560                         rv = (Bigint*)MALLOC(len*sizeof(double));
561 #endif
562                 rv->k = k;
563                 rv->maxwds = x;
564                 }
565         FREE_DTOA_LOCK(0);
566         rv->sign = rv->wds = 0;
567         return rv;
568         }
569
570  static void
571 Bfree
572 #ifdef KR_headers
573         (v) Bigint *v;
574 #else
575         (Bigint *v)
576 #endif
577 {
578 #ifdef Omit_Private_Memory
579         free (v);
580 #else
581         if (v) {
582                 ACQUIRE_DTOA_LOCK(0);
583                 v->next = freelist[v->k];
584                 freelist[v->k] = v;
585                 FREE_DTOA_LOCK(0);
586         }
587 #endif
588 }
589
590 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
591 y->wds*sizeof(Long) + 2*sizeof(int))
592
593  static Bigint *
594 multadd
595 #ifdef KR_headers
596         (b, m, a) Bigint *b; int m, a;
597 #else
598         (Bigint *b, int m, int a)       /* multiply by m and add a */
599 #endif
600 {
601         int i, wds;
602 #ifdef ULLong
603         ULong *x;
604         ULLong carry, y;
605 #else
606         ULong carry, *x, y;
607 #ifdef Pack_32
608         ULong xi, z;
609 #endif
610 #endif
611         Bigint *b1;
612
613         wds = b->wds;
614         x = b->x;
615         i = 0;
616         carry = a;
617         do {
618 #ifdef ULLong
619                 y = *x * (ULLong)m + carry;
620                 carry = y >> 32;
621                 *x++ = y & FFFFFFFF;
622 #else
623 #ifdef Pack_32
624                 xi = *x;
625                 y = (xi & 0xffff) * m + carry;
626                 z = (xi >> 16) * m + (y >> 16);
627                 carry = z >> 16;
628                 *x++ = (z << 16) + (y & 0xffff);
629 #else
630                 y = *x * m + carry;
631                 carry = y >> 16;
632                 *x++ = y & 0xffff;
633 #endif
634 #endif
635                 }
636                 while(++i < wds);
637         if (carry) {
638                 if (wds >= b->maxwds) {
639                         b1 = Balloc(b->k+1);
640                         Bcopy(b1, b);
641                         Bfree(b);
642                         b = b1;
643                         }
644                 b->x[wds++] = carry;
645                 b->wds = wds;
646                 }
647         return b;
648         }
649
650  static Bigint *
651 s2b
652 #ifdef KR_headers
653         (s, nd0, nd, y9) CONST char *s; int nd0, nd; ULong y9;
654 #else
655         (CONST char *s, int nd0, int nd, ULong y9)
656 #endif
657 {
658         Bigint *b;
659         int i, k;
660         Long x, y;
661
662         x = (nd + 8) / 9;
663         for(k = 0, y = 1; x > y; y <<= 1, k++) ;
664 #ifdef Pack_32
665         b = Balloc(k);
666         b->x[0] = y9;
667         b->wds = 1;
668 #else
669         b = Balloc(k+1);
670         b->x[0] = y9 & 0xffff;
671         b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
672 #endif
673
674         i = 9;
675         if (9 < nd0) {
676                 s += 9;
677                 do b = multadd(b, 10, *s++ - '0');
678                         while(++i < nd0);
679                 s++;
680                 }
681         else
682                 s += 10;
683         for(; i < nd; i++)
684                 b = multadd(b, 10, *s++ - '0');
685         return b;
686         }
687
688  static int
689 hi0bits
690 #ifdef KR_headers
691         (x) register ULong x;
692 #else
693         (register ULong x)
694 #endif
695 {
696         register int k = 0;
697
698         if (!(x & 0xffff0000)) {
699                 k = 16;
700                 x <<= 16;
701                 }
702         if (!(x & 0xff000000)) {
703                 k += 8;
704                 x <<= 8;
705                 }
706         if (!(x & 0xf0000000)) {
707                 k += 4;
708                 x <<= 4;
709                 }
710         if (!(x & 0xc0000000)) {
711                 k += 2;
712                 x <<= 2;
713                 }
714         if (!(x & 0x80000000)) {
715                 k++;
716                 if (!(x & 0x40000000))
717                         return 32;
718                 }
719         return k;
720         }
721
722  static int
723 lo0bits
724 #ifdef KR_headers
725         (y) ULong *y;
726 #else
727         (ULong *y)
728 #endif
729 {
730         register int k;
731         register ULong x = *y;
732
733         if (x & 7) {
734                 if (x & 1)
735                         return 0;
736                 if (x & 2) {
737                         *y = x >> 1;
738                         return 1;
739                         }
740                 *y = x >> 2;
741                 return 2;
742                 }
743         k = 0;
744         if (!(x & 0xffff)) {
745                 k = 16;
746                 x >>= 16;
747                 }
748         if (!(x & 0xff)) {
749                 k += 8;
750                 x >>= 8;
751                 }
752         if (!(x & 0xf)) {
753                 k += 4;
754                 x >>= 4;
755                 }
756         if (!(x & 0x3)) {
757                 k += 2;
758                 x >>= 2;
759                 }
760         if (!(x & 1)) {
761                 k++;
762                 x >>= 1;
763                 if (!x)
764                         return 32;
765                 }
766         *y = x;
767         return k;
768         }
769
770  static Bigint *
771 i2b
772 #ifdef KR_headers
773         (i) int i;
774 #else
775         (int i)
776 #endif
777 {
778         Bigint *b;
779
780         b = Balloc(1);
781         b->x[0] = i;
782         b->wds = 1;
783         return b;
784         }
785
786  static Bigint *
787 mult
788 #ifdef KR_headers
789         (a, b) Bigint *a, *b;
790 #else
791         (Bigint *a, Bigint *b)
792 #endif
793 {
794         Bigint *c;
795         int k, wa, wb, wc;
796         ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
797         ULong y;
798 #ifdef ULLong
799         ULLong carry, z;
800 #else
801         ULong carry, z;
802 #ifdef Pack_32
803         ULong z2;
804 #endif
805 #endif
806
807         if (a->wds < b->wds) {
808                 c = a;
809                 a = b;
810                 b = c;
811                 }
812         k = a->k;
813         wa = a->wds;
814         wb = b->wds;
815         wc = wa + wb;
816         if (wc > a->maxwds)
817                 k++;
818         c = Balloc(k);
819         for(x = c->x, xa = x + wc; x < xa; x++)
820                 *x = 0;
821         xa = a->x;
822         xae = xa + wa;
823         xb = b->x;
824         xbe = xb + wb;
825         xc0 = c->x;
826 #ifdef ULLong
827         for(; xb < xbe; xc0++) {
828                 if ((y = *xb++)) {
829                         x = xa;
830                         xc = xc0;
831                         carry = 0;
832                         do {
833                                 z = *x++ * (ULLong)y + *xc + carry;
834                                 carry = z >> 32;
835                                 *xc++ = z & FFFFFFFF;
836                                 }
837                                 while(x < xae);
838                         *xc = carry;
839                         }
840                 }
841 #else
842 #ifdef Pack_32
843         for(; xb < xbe; xb++, xc0++) {
844                 if (y = *xb & 0xffff) {
845                         x = xa;
846                         xc = xc0;
847                         carry = 0;
848                         do {
849                                 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
850                                 carry = z >> 16;
851                                 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
852                                 carry = z2 >> 16;
853                                 Storeinc(xc, z2, z);
854                                 }
855                                 while(x < xae);
856                         *xc = carry;
857                         }
858                 if (y = *xb >> 16) {
859                         x = xa;
860                         xc = xc0;
861                         carry = 0;
862                         z2 = *xc;
863                         do {
864                                 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
865                                 carry = z >> 16;
866                                 Storeinc(xc, z, z2);
867                                 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
868                                 carry = z2 >> 16;
869                                 }
870                                 while(x < xae);
871                         *xc = z2;
872                         }
873                 }
874 #else
875         for(; xb < xbe; xc0++) {
876                 if (y = *xb++) {
877                         x = xa;
878                         xc = xc0;
879                         carry = 0;
880                         do {
881                                 z = *x++ * y + *xc + carry;
882                                 carry = z >> 16;
883                                 *xc++ = z & 0xffff;
884                                 }
885                                 while(x < xae);
886                         *xc = carry;
887                         }
888                 }
889 #endif
890 #endif
891         for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
892         c->wds = wc;
893         return c;
894         }
895
896  static Bigint *p5s;
897
898  static Bigint *
899 pow5mult
900 #ifdef KR_headers
901         (b, k) Bigint *b; int k;
902 #else
903         (Bigint *b, int k)
904 #endif
905 {
906         Bigint *b1, *p5, *p51;
907         int i;
908         static int p05[3] = { 5, 25, 125 };
909
910         if ((i = k & 3))
911                 b = multadd(b, p05[i-1], 0);
912
913         if (!(k >>= 2))
914                 return b;
915         if (!(p5 = p5s)) {
916                 /* first time */
917 #ifdef MULTIPLE_THREADS
918                 ACQUIRE_DTOA_LOCK(1);
919                 if (!(p5 = p5s)) {
920                         p5 = p5s = i2b(625);
921                         p5->next = 0;
922                         }
923                 FREE_DTOA_LOCK(1);
924 #else
925                 p5 = p5s = i2b(625);
926                 p5->next = 0;
927 #endif
928                 }
929         for(;;) {
930                 if (k & 1) {
931                         b1 = mult(b, p5);
932                         Bfree(b);
933                         b = b1;
934                         }
935                 if (!(k >>= 1))
936                         break;
937                 if (!(p51 = p5->next)) {
938 #ifdef MULTIPLE_THREADS
939                         ACQUIRE_DTOA_LOCK(1);
940                         if (!(p51 = p5->next)) {
941                                 p51 = p5->next = mult(p5,p5);
942                                 p51->next = 0;
943                                 }
944                         FREE_DTOA_LOCK(1);
945 #else
946                         p51 = p5->next = mult(p5,p5);
947                         p51->next = 0;
948 #endif
949                         }
950                 p5 = p51;
951                 }
952         return b;
953         }
954
955  static Bigint *
956 lshift
957 #ifdef KR_headers
958         (b, k) Bigint *b; int k;
959 #else
960         (Bigint *b, int k)
961 #endif
962 {
963         int i, k1, n, n1;
964         Bigint *b1;
965         ULong *x, *x1, *xe, z;
966
967 #ifdef Pack_32
968         n = k >> 5;
969 #else
970         n = k >> 4;
971 #endif
972         k1 = b->k;
973         n1 = n + b->wds + 1;
974         for(i = b->maxwds; n1 > i; i <<= 1)
975                 k1++;
976         b1 = Balloc(k1);
977         x1 = b1->x;
978         for(i = 0; i < n; i++)
979                 *x1++ = 0;
980         x = b->x;
981         xe = x + b->wds;
982 #ifdef Pack_32
983         if (k &= 0x1f) {
984                 k1 = 32 - k;
985                 z = 0;
986                 do {
987                         *x1++ = *x << k | z;
988                         z = *x++ >> k1;
989                         }
990                         while(x < xe);
991                 if ((*x1 = z))
992                         ++n1;
993                 }
994 #else
995         if (k &= 0xf) {
996                 k1 = 16 - k;
997                 z = 0;
998                 do {
999                         *x1++ = *x << k  & 0xffff | z;
1000                         z = *x++ >> k1;
1001                         }
1002                         while(x < xe);
1003                 if (*x1 = z)
1004                         ++n1;
1005                 }
1006 #endif
1007         else do
1008                 *x1++ = *x++;
1009                 while(x < xe);
1010         b1->wds = n1 - 1;
1011         Bfree(b);
1012         return b1;
1013         }
1014
1015  static int
1016 cmp
1017 #ifdef KR_headers
1018         (a, b) Bigint *a, *b;
1019 #else
1020         (Bigint *a, Bigint *b)
1021 #endif
1022 {
1023         ULong *xa, *xa0, *xb, *xb0;
1024         int i, j;
1025
1026         i = a->wds;
1027         j = b->wds;
1028 #ifdef DEBUG
1029         if (i > 1 && !a->x[i-1])
1030                 Bug("cmp called with a->x[a->wds-1] == 0");
1031         if (j > 1 && !b->x[j-1])
1032                 Bug("cmp called with b->x[b->wds-1] == 0");
1033 #endif
1034         if (i -= j)
1035                 return i;
1036         xa0 = a->x;
1037         xa = xa0 + j;
1038         xb0 = b->x;
1039         xb = xb0 + j;
1040         for(;;) {
1041                 if (*--xa != *--xb)
1042                         return *xa < *xb ? -1 : 1;
1043                 if (xa <= xa0)
1044                         break;
1045                 }
1046         return 0;
1047         }
1048
1049  static Bigint *
1050 diff
1051 #ifdef KR_headers
1052         (a, b) Bigint *a, *b;
1053 #else
1054         (Bigint *a, Bigint *b)
1055 #endif
1056 {
1057         Bigint *c;
1058         int i, wa, wb;
1059         ULong *xa, *xae, *xb, *xbe, *xc;
1060 #ifdef ULLong
1061         ULLong borrow, y;
1062 #else
1063         ULong borrow, y;
1064 #ifdef Pack_32
1065         ULong z;
1066 #endif
1067 #endif
1068
1069         i = cmp(a,b);
1070         if (!i) {
1071                 c = Balloc(0);
1072                 c->wds = 1;
1073                 c->x[0] = 0;
1074                 return c;
1075                 }
1076         if (i < 0) {
1077                 c = a;
1078                 a = b;
1079                 b = c;
1080                 i = 1;
1081                 }
1082         else
1083                 i = 0;
1084         c = Balloc(a->k);
1085         c->sign = i;
1086         wa = a->wds;
1087         xa = a->x;
1088         xae = xa + wa;
1089         wb = b->wds;
1090         xb = b->x;
1091         xbe = xb + wb;
1092         xc = c->x;
1093         borrow = 0;
1094 #ifdef ULLong
1095         do {
1096                 y = (ULLong)*xa++ - *xb++ - borrow;
1097                 borrow = y >> 32 & (ULong)1;
1098                 *xc++ = y & FFFFFFFF;
1099                 }
1100                 while(xb < xbe);
1101         while(xa < xae) {
1102                 y = *xa++ - borrow;
1103                 borrow = y >> 32 & (ULong)1;
1104                 *xc++ = y & FFFFFFFF;
1105                 }
1106 #else
1107 #ifdef Pack_32
1108         do {
1109                 y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
1110                 borrow = (y & 0x10000) >> 16;
1111                 z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
1112                 borrow = (z & 0x10000) >> 16;
1113                 Storeinc(xc, z, y);
1114                 }
1115                 while(xb < xbe);
1116         while(xa < xae) {
1117                 y = (*xa & 0xffff) - borrow;
1118                 borrow = (y & 0x10000) >> 16;
1119                 z = (*xa++ >> 16) - borrow;
1120                 borrow = (z & 0x10000) >> 16;
1121                 Storeinc(xc, z, y);
1122                 }
1123 #else
1124         do {
1125                 y = *xa++ - *xb++ - borrow;
1126                 borrow = (y & 0x10000) >> 16;
1127                 *xc++ = y & 0xffff;
1128                 }
1129                 while(xb < xbe);
1130         while(xa < xae) {
1131                 y = *xa++ - borrow;
1132                 borrow = (y & 0x10000) >> 16;
1133                 *xc++ = y & 0xffff;
1134                 }
1135 #endif
1136 #endif
1137         while(!*--xc)
1138                 wa--;
1139         c->wds = wa;
1140         return c;
1141         }
1142
1143  static double
1144 ulp
1145 #ifdef KR_headers
1146         (x) double x;
1147 #else
1148         (double x)
1149 #endif
1150 {
1151         register Long L;
1152         double a;
1153
1154         L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
1155 #ifndef Avoid_Underflow
1156 #ifndef Sudden_Underflow
1157         if (L > 0) {
1158 #endif
1159 #endif
1160 #ifdef IBM
1161                 L |= Exp_msk1 >> 4;
1162 #endif
1163                 word0(a) = L;
1164                 word1(a) = 0;
1165 #ifndef Avoid_Underflow
1166 #ifndef Sudden_Underflow
1167                 }
1168         else {
1169                 L = -L >> Exp_shift;
1170                 if (L < Exp_shift) {
1171                         word0(a) = 0x80000 >> L;
1172                         word1(a) = 0;
1173                         }
1174                 else {
1175                         word0(a) = 0;
1176                         L -= Exp_shift;
1177                         word1(a) = L >= 31 ? 1 : 1 << 31 - L;
1178                         }
1179                 }
1180 #endif
1181 #endif
1182         return dval(a);
1183         }
1184
1185  static double
1186 b2d
1187 #ifdef KR_headers
1188         (a, e) Bigint *a; int *e;
1189 #else
1190         (Bigint *a, int *e)
1191 #endif
1192 {
1193         ULong *xa, *xa0, w, y, z;
1194         int k;
1195         double d;
1196 #ifdef VAX
1197         ULong d0, d1;
1198 #else
1199 #define d0 word0(d)
1200 #define d1 word1(d)
1201 #endif
1202
1203         xa0 = a->x;
1204         xa = xa0 + a->wds;
1205         y = *--xa;
1206 #ifdef DEBUG
1207         if (!y) Bug("zero y in b2d");
1208 #endif
1209         k = hi0bits(y);
1210         *e = 32 - k;
1211 #ifdef Pack_32
1212         if (k < Ebits) {
1213                 d0 = Exp_1 | (y >> (Ebits - k));
1214                 w = xa > xa0 ? *--xa : 0;
1215                 d1 = y << ((32-Ebits) + k) | (w >> (Ebits - k));
1216                 goto ret_d;
1217                 }
1218         z = xa > xa0 ? *--xa : 0;
1219         if (k -= Ebits) {
1220                 d0 = Exp_1 | y << k | (z >> (32 - k));
1221                 y = xa > xa0 ? *--xa : 0;
1222                 d1 = z << k | (y >> (32 - k));
1223                 }
1224         else {
1225                 d0 = Exp_1 | y;
1226                 d1 = z;
1227                 }
1228 #else
1229         if (k < Ebits + 16) {
1230                 z = xa > xa0 ? *--xa : 0;
1231                 d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
1232                 w = xa > xa0 ? *--xa : 0;
1233                 y = xa > xa0 ? *--xa : 0;
1234                 d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
1235                 goto ret_d;
1236                 }
1237         z = xa > xa0 ? *--xa : 0;
1238         w = xa > xa0 ? *--xa : 0;
1239         k -= Ebits + 16;
1240         d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
1241         y = xa > xa0 ? *--xa : 0;
1242         d1 = w << k + 16 | y << k;
1243 #endif
1244  ret_d:
1245 #ifdef VAX
1246         word0(d) = d0 >> 16 | d0 << 16;
1247         word1(d) = d1 >> 16 | d1 << 16;
1248 #else
1249 #undef d0
1250 #undef d1
1251 #endif
1252         return dval(d);
1253         }
1254
1255  static Bigint *
1256 d2b
1257 #ifdef KR_headers
1258         (d, e, bits) double d; int *e, *bits;
1259 #else
1260         (double d, int *e, int *bits)
1261 #endif
1262 {
1263         Bigint *b;
1264         int de, k;
1265         ULong *x, y, z;
1266 #ifndef Sudden_Underflow
1267         int i;
1268 #endif
1269 #ifdef VAX
1270         ULong d0, d1;
1271         d0 = word0(d) >> 16 | word0(d) << 16;
1272         d1 = word1(d) >> 16 | word1(d) << 16;
1273 #else
1274 #define d0 word0(d)
1275 #define d1 word1(d)
1276 #endif
1277
1278 #ifdef Pack_32
1279         b = Balloc(1);
1280 #else
1281         b = Balloc(2);
1282 #endif
1283         x = b->x;
1284
1285         z = d0 & Frac_mask;
1286         d0 &= 0x7fffffff;       /* clear sign bit, which we ignore */
1287 #ifdef Sudden_Underflow
1288         de = (int)(d0 >> Exp_shift);
1289 #ifndef IBM
1290         z |= Exp_msk11;
1291 #endif
1292 #else
1293         if ((de = (int)(d0 >> Exp_shift)))
1294                 z |= Exp_msk1;
1295 #endif
1296 #ifdef Pack_32
1297         if ((y = d1)) {
1298                 if ((k = lo0bits(&y))) {
1299                         x[0] = y | (z << (32 - k));
1300                         z >>= k;
1301                         }
1302                 else
1303                         x[0] = y;
1304 #ifndef Sudden_Underflow
1305                 i =
1306 #endif
1307                     b->wds = (x[1] = z) ? 2 : 1;
1308                 }
1309         else {
1310 #ifdef DEBUG
1311                 if (!z)
1312                         Bug("Zero passed to d2b");
1313 #endif
1314                 k = lo0bits(&z);
1315                 x[0] = z;
1316 #ifndef Sudden_Underflow
1317                 i =
1318 #endif
1319                     b->wds = 1;
1320                 k += 32;
1321                 }
1322 #else
1323         if (y = d1) {
1324                 if (k = lo0bits(&y))
1325                         if (k >= 16) {
1326                                 x[0] = y | z << 32 - k & 0xffff;
1327                                 x[1] = z >> k - 16 & 0xffff;
1328                                 x[2] = z >> k;
1329                                 i = 2;
1330                                 }
1331                         else {
1332                                 x[0] = y & 0xffff;
1333                                 x[1] = y >> 16 | z << 16 - k & 0xffff;
1334                                 x[2] = z >> k & 0xffff;
1335                                 x[3] = z >> k+16;
1336                                 i = 3;
1337                                 }
1338                 else {
1339                         x[0] = y & 0xffff;
1340                         x[1] = y >> 16;
1341                         x[2] = z & 0xffff;
1342                         x[3] = z >> 16;
1343                         i = 3;
1344                         }
1345                 }
1346         else {
1347 #ifdef DEBUG
1348                 if (!z)
1349                         Bug("Zero passed to d2b");
1350 #endif
1351                 k = lo0bits(&z);
1352                 if (k >= 16) {
1353                         x[0] = z;
1354                         i = 0;
1355                         }
1356                 else {
1357                         x[0] = z & 0xffff;
1358                         x[1] = z >> 16;
1359                         i = 1;
1360                         }
1361                 k += 32;
1362                 }
1363         while(!x[i])
1364                 --i;
1365         b->wds = i + 1;
1366 #endif
1367 #ifndef Sudden_Underflow
1368         if (de) {
1369 #endif
1370 #ifdef IBM
1371                 *e = (de - Bias - (P-1) << 2) + k;
1372                 *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
1373 #else
1374                 *e = de - Bias - (P-1) + k;
1375                 *bits = P - k;
1376 #endif
1377 #ifndef Sudden_Underflow
1378                 }
1379         else {
1380                 *e = de - Bias - (P-1) + 1 + k;
1381 #ifdef Pack_32
1382                 *bits = 32*i - hi0bits(x[i-1]);
1383 #else
1384                 *bits = (i+2)*16 - hi0bits(x[i]);
1385 #endif
1386                 }
1387 #endif
1388         return b;
1389         }
1390 #undef d0
1391 #undef d1
1392
1393  static double
1394 ratio
1395 #ifdef KR_headers
1396         (a, b) Bigint *a, *b;
1397 #else
1398         (Bigint *a, Bigint *b)
1399 #endif
1400 {
1401         double da, db;
1402         int k, ka, kb;
1403
1404         dval(da) = b2d(a, &ka);
1405         dval(db) = b2d(b, &kb);
1406 #ifdef Pack_32
1407         k = ka - kb + 32*(a->wds - b->wds);
1408 #else
1409         k = ka - kb + 16*(a->wds - b->wds);
1410 #endif
1411 #ifdef IBM
1412         if (k > 0) {
1413                 word0(da) += (k >> 2)*Exp_msk1;
1414                 if (k &= 3)
1415                         dval(da) *= 1 << k;
1416                 }
1417         else {
1418                 k = -k;
1419                 word0(db) += (k >> 2)*Exp_msk1;
1420                 if (k &= 3)
1421                         dval(db) *= 1 << k;
1422                 }
1423 #else
1424         if (k > 0)
1425                 word0(da) += k*Exp_msk1;
1426         else {
1427                 k = -k;
1428                 word0(db) += k*Exp_msk1;
1429                 }
1430 #endif
1431         return dval(da) / dval(db);
1432         }
1433
1434  static CONST double
1435 tens[] = {
1436                 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1437                 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1438                 1e20, 1e21, 1e22
1439 #ifdef VAX
1440                 , 1e23, 1e24
1441 #endif
1442                 };
1443
1444  static CONST double
1445 #ifdef IEEE_Arith
1446 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
1447 static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
1448 #ifdef Avoid_Underflow
1449                 9007199254740992.*9007199254740992.e-256
1450                 /* = 2^106 * 1e-53 */
1451 #else
1452                 1e-256
1453 #endif
1454                 };
1455 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
1456 /* flag unnecessarily.  It leads to a song and dance at the end of strtod. */
1457 #define Scale_Bit 0x10
1458 #define n_bigtens 5
1459 #else
1460 #ifdef IBM
1461 bigtens[] = { 1e16, 1e32, 1e64 };
1462 static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64 };
1463 #define n_bigtens 3
1464 #else
1465 bigtens[] = { 1e16, 1e32 };
1466 static CONST double tinytens[] = { 1e-16, 1e-32 };
1467 #define n_bigtens 2
1468 #endif
1469 #endif
1470
1471 #ifndef IEEE_Arith
1472 #undef INFNAN_CHECK
1473 #endif
1474
1475 #ifdef INFNAN_CHECK
1476
1477 #ifndef NAN_WORD0
1478 #define NAN_WORD0 0x7ff80000
1479 #endif
1480
1481 #ifndef NAN_WORD1
1482 #define NAN_WORD1 0
1483 #endif
1484
1485  static int
1486 match
1487 #ifdef KR_headers
1488         (sp, t) char **sp, *t;
1489 #else
1490         (CONST char **sp, char *t)
1491 #endif
1492 {
1493         int c, d;
1494         CONST char *s = *sp;
1495
1496         while(d = *t++) {
1497                 if ((c = *++s) >= 'A' && c <= 'Z')
1498                         c += 'a' - 'A';
1499                 if (c != d)
1500                         return 0;
1501                 }
1502         *sp = s + 1;
1503         return 1;
1504         }
1505
1506 #ifndef No_Hex_NaN
1507  static void
1508 hexnan
1509 #ifdef KR_headers
1510         (rvp, sp) double *rvp; CONST char **sp;
1511 #else
1512         (double *rvp, CONST char **sp)
1513 #endif
1514 {
1515         ULong c, x[2];
1516         CONST char *s;
1517         int havedig, udx0, xshift;
1518
1519         x[0] = x[1] = 0;
1520         havedig = xshift = 0;
1521         udx0 = 1;
1522         s = *sp;
1523         while(c = *(CONST unsigned char*)++s) {
1524                 if (c >= '0' && c <= '9')
1525                         c -= '0';
1526                 else if (c >= 'a' && c <= 'f')
1527                         c += 10 - 'a';
1528                 else if (c >= 'A' && c <= 'F')
1529                         c += 10 - 'A';
1530                 else if (c <= ' ') {
1531                         if (udx0 && havedig) {
1532                                 udx0 = 0;
1533                                 xshift = 1;
1534                                 }
1535                         continue;
1536                         }
1537                 else if (/*(*/ c == ')' && havedig) {
1538                         *sp = s + 1;
1539                         break;
1540                         }
1541                 else
1542                         return; /* invalid form: don't change *sp */
1543                 havedig = 1;
1544                 if (xshift) {
1545                         xshift = 0;
1546                         x[0] = x[1];
1547                         x[1] = 0;
1548                         }
1549                 if (udx0)
1550                         x[0] = (x[0] << 4) | (x[1] >> 28);
1551                 x[1] = (x[1] << 4) | c;
1552                 }
1553         if ((x[0] &= 0xfffff) || x[1]) {
1554                 word0(*rvp) = Exp_mask | x[0];
1555                 word1(*rvp) = x[1];
1556                 }
1557         }
1558 #endif /*No_Hex_NaN*/
1559 #endif /* INFNAN_CHECK */
1560
1561         /*
1562          * LOCKING: This is not thread-safe, since the locking macros are defined as no-ops,
1563          * the caller should lock.
1564          */
1565
1566  double
1567 mono_strtod
1568 #ifdef KR_headers
1569         (s00, se) CONST char *s00; char **se;
1570 #else
1571         (CONST char *s00, char **se)
1572 #endif
1573 {
1574 #ifdef Avoid_Underflow
1575         int scale;
1576 #endif
1577         int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
1578                  e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1579         CONST char *s, *s0, *s1;
1580         double aadj, aadj1, adj, rv, rv0;
1581         Long L;
1582         ULong y, z;
1583         Bigint *bb = NULL, *bb1, *bd = NULL, *bd0, *bs = NULL, *delta = NULL;
1584 #ifdef SET_INEXACT
1585         int inexact, oldinexact;
1586 #endif
1587 #ifdef Honor_FLT_ROUNDS
1588         int rounding;
1589 #endif
1590 #ifdef USE_LOCALE
1591         CONST char *s2;
1592 #endif
1593
1594         sign = nz0 = nz = 0;
1595         dval(rv) = 0.;
1596         for(s = s00;;s++) switch(*s) {
1597                 case '-':
1598                         sign = 1;
1599                         /* no break */
1600                 case '+':
1601                         if (*++s)
1602                                 goto break2;
1603                         /* no break */
1604                 case 0:
1605                         goto ret0;
1606                 case '\t':
1607                 case '\n':
1608                 case '\v':
1609                 case '\f':
1610                 case '\r':
1611                 case ' ':
1612                         continue;
1613                 default:
1614                         goto break2;
1615                 }
1616  break2:
1617         if (*s == '0') {
1618                 nz0 = 1;
1619                 while(*++s == '0') ;
1620                 if (!*s)
1621                         goto ret;
1622                 }
1623         s0 = s;
1624         y = z = 0;
1625         for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
1626                 if (nd < 9)
1627                         y = 10*y + c - '0';
1628                 else if (nd < 16)
1629                         z = 10*z + c - '0';
1630         nd0 = nd;
1631 #ifdef USE_LOCALE
1632         s1 = localeconv()->decimal_point;
1633         if (c == *s1) {
1634                 c = '.';
1635                 if (*++s1) {
1636                         s2 = s;
1637                         for(;;) {
1638                                 if (*++s2 != *s1) {
1639                                         c = 0;
1640                                         break;
1641                                         }
1642                                 if (!*++s1) {
1643                                         s = s2;
1644                                         break;
1645                                         }
1646                                 }
1647                         }
1648                 }
1649 #endif
1650         if (c == '.') {
1651                 c = *++s;
1652                 if (!nd) {
1653                         for(; c == '0'; c = *++s)
1654                                 nz++;
1655                         if (c > '0' && c <= '9') {
1656                                 s0 = s;
1657                                 nf += nz;
1658                                 nz = 0;
1659                                 goto have_dig;
1660                                 }
1661                         goto dig_done;
1662                         }
1663                 for(; c >= '0' && c <= '9'; c = *++s) {
1664  have_dig:
1665                         nz++;
1666                         if (c -= '0') {
1667                                 nf += nz;
1668                                 for(i = 1; i < nz; i++)
1669                                         if (nd++ < 9)
1670                                                 y *= 10;
1671                                         else if (nd <= DBL_DIG + 1)
1672                                                 z *= 10;
1673                                 if (nd++ < 9)
1674                                         y = 10*y + c;
1675                                 else if (nd <= DBL_DIG + 1)
1676                                         z = 10*z + c;
1677                                 nz = 0;
1678                                 }
1679                         }
1680                 }
1681  dig_done:
1682         e = 0;
1683         if (c == 'e' || c == 'E') {
1684                 if (!nd && !nz && !nz0) {
1685                         goto ret0;
1686                         }
1687                 s00 = s;
1688                 esign = 0;
1689                 switch(c = *++s) {
1690                         case '-':
1691                                 esign = 1;
1692                         case '+':
1693                                 c = *++s;
1694                         }
1695                 if (c >= '0' && c <= '9') {
1696                         while(c == '0')
1697                                 c = *++s;
1698                         if (c > '0' && c <= '9') {
1699                                 L = c - '0';
1700                                 s1 = s;
1701                                 while((c = *++s) >= '0' && c <= '9')
1702                                         L = 10*L + c - '0';
1703                                 if (s - s1 > 8 || L > 19999)
1704                                         /* Avoid confusion from exponents
1705                                          * so large that e might overflow.
1706                                          */
1707                                         e = 19999; /* safe for 16 bit ints */
1708                                 else
1709                                         e = (int)L;
1710                                 if (esign)
1711                                         e = -e;
1712                                 }
1713                         else
1714                                 e = 0;
1715                         }
1716                 else
1717                         s = s00;
1718                 }
1719         if (!nd) {
1720                 if (!nz && !nz0) {
1721 #ifdef INFNAN_CHECK
1722                         /* Check for Nan and Infinity */
1723                         switch(c) {
1724                           case 'i':
1725                           case 'I':
1726                                 if (match(&s,"nf")) {
1727                                         --s;
1728                                         if (!match(&s,"inity"))
1729                                                 ++s;
1730                                         word0(rv) = 0x7ff00000;
1731                                         word1(rv) = 0;
1732                                         goto ret;
1733                                         }
1734                                 break;
1735                           case 'n':
1736                           case 'N':
1737                                 if (match(&s, "an")) {
1738                                         word0(rv) = NAN_WORD0;
1739                                         word1(rv) = NAN_WORD1;
1740 #ifndef No_Hex_NaN
1741                                         if (*s == '(') /*)*/
1742                                                 hexnan(&rv, &s);
1743 #endif
1744                                         goto ret;
1745                                         }
1746                           }
1747 #endif /* INFNAN_CHECK */
1748  ret0:
1749                         s = s00;
1750                         sign = 0;
1751                         }
1752                 goto ret;
1753                 }
1754         e1 = e -= nf;
1755
1756         /* Now we have nd0 digits, starting at s0, followed by a
1757          * decimal point, followed by nd-nd0 digits.  The number we're
1758          * after is the integer represented by those digits times
1759          * 10**e */
1760
1761         if (!nd0)
1762                 nd0 = nd;
1763         k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1764         dval(rv) = y;
1765         if (k > 9) {
1766 #ifdef SET_INEXACT
1767                 if (k > DBL_DIG)
1768                         oldinexact = get_inexact();
1769 #endif
1770                 dval(rv) = tens[k - 9] * dval(rv) + z;
1771                 }
1772         bd0 = 0;
1773         if (nd <= DBL_DIG
1774 #ifndef RND_PRODQUOT
1775 #ifndef Honor_FLT_ROUNDS
1776                 && Flt_Rounds == 1
1777 #endif
1778 #endif
1779                         ) {
1780                 if (!e)
1781                         goto ret;
1782                 if (e > 0) {
1783                         if (e <= Ten_pmax) {
1784 #ifdef VAX
1785                                 goto vax_ovfl_check;
1786 #else
1787 #ifdef Honor_FLT_ROUNDS
1788                                 /* round correctly FLT_ROUNDS = 2 or 3 */
1789                                 if (sign) {
1790                                         rv = -rv;
1791                                         sign = 0;
1792                                         }
1793 #endif
1794                                 /* rv = */ rounded_product(dval(rv), tens[e]);
1795                                 goto ret;
1796 #endif
1797                                 }
1798                         i = DBL_DIG - nd;
1799                         if (e <= Ten_pmax + i) {
1800                                 /* A fancier test would sometimes let us do
1801                                  * this for larger i values.
1802                                  */
1803 #ifdef Honor_FLT_ROUNDS
1804                                 /* round correctly FLT_ROUNDS = 2 or 3 */
1805                                 if (sign) {
1806                                         rv = -rv;
1807                                         sign = 0;
1808                                         }
1809 #endif
1810                                 e -= i;
1811                                 dval(rv) *= tens[i];
1812 #ifdef VAX
1813                                 /* VAX exponent range is so narrow we must
1814                                  * worry about overflow here...
1815                                  */
1816  vax_ovfl_check:
1817                                 word0(rv) -= P*Exp_msk1;
1818                                 /* rv = */ rounded_product(dval(rv), tens[e]);
1819                                 if ((word0(rv) & Exp_mask)
1820                                  > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
1821                                         goto ovfl;
1822                                 word0(rv) += P*Exp_msk1;
1823 #else
1824                                 /* rv = */ rounded_product(dval(rv), tens[e]);
1825 #endif
1826                                 goto ret;
1827                                 }
1828                         }
1829 #ifndef Inaccurate_Divide
1830                 else if (e >= -Ten_pmax) {
1831 #ifdef Honor_FLT_ROUNDS
1832                         /* round correctly FLT_ROUNDS = 2 or 3 */
1833                         if (sign) {
1834                                 rv = -rv;
1835                                 sign = 0;
1836                                 }
1837 #endif
1838                         /* rv = */ rounded_quotient(dval(rv), tens[-e]);
1839                         goto ret;
1840                         }
1841 #endif
1842                 }
1843         e1 += nd - k;
1844
1845 #ifdef IEEE_Arith
1846 #ifdef SET_INEXACT
1847         inexact = 1;
1848         if (k <= DBL_DIG)
1849                 oldinexact = get_inexact();
1850 #endif
1851 #ifdef Avoid_Underflow
1852         scale = 0;
1853 #endif
1854 #ifdef Honor_FLT_ROUNDS
1855         if ((rounding = Flt_Rounds) >= 2) {
1856                 if (sign)
1857                         rounding = rounding == 2 ? 0 : 2;
1858                 else
1859                         if (rounding != 2)
1860                                 rounding = 0;
1861                 }
1862 #endif
1863 #endif /*IEEE_Arith*/
1864
1865         /* Get starting approximation = rv * 10**e1 */
1866
1867         if (e1 > 0) {
1868                 if ((i = e1 & 15))
1869                         dval(rv) *= tens[i];
1870                 if (e1 &= ~15) {
1871                         if (e1 > DBL_MAX_10_EXP) {
1872  ovfl:
1873 #ifndef NO_ERRNO
1874                                 errno = ERANGE;
1875 #endif
1876                                 /* Can't trust HUGE_VAL */
1877 #ifdef IEEE_Arith
1878 #ifdef Honor_FLT_ROUNDS
1879                                 switch(rounding) {
1880                                   case 0: /* toward 0 */
1881                                   case 3: /* toward -infinity */
1882                                         word0(rv) = Big0;
1883                                         word1(rv) = Big1;
1884                                         break;
1885                                   default:
1886                                         word0(rv) = Exp_mask;
1887                                         word1(rv) = 0;
1888                                   }
1889 #else /*Honor_FLT_ROUNDS*/
1890                                 word0(rv) = Exp_mask;
1891                                 word1(rv) = 0;
1892 #endif /*Honor_FLT_ROUNDS*/
1893 #ifdef SET_INEXACT
1894                                 /* set overflow bit */
1895                                 dval(rv0) = 1e300;
1896                                 dval(rv0) *= dval(rv0);
1897 #endif
1898 #else /*IEEE_Arith*/
1899                                 word0(rv) = Big0;
1900                                 word1(rv) = Big1;
1901 #endif /*IEEE_Arith*/
1902                                 if (bd0)
1903                                         goto retfree;
1904                                 goto ret;
1905                                 }
1906                         e1 >>= 4;
1907                         for(j = 0; e1 > 1; j++, e1 >>= 1)
1908                                 if (e1 & 1)
1909                                         dval(rv) *= bigtens[j];
1910                 /* The last multiplication could overflow. */
1911                         word0(rv) -= P*Exp_msk1;
1912                         dval(rv) *= bigtens[j];
1913                         if ((z = word0(rv) & Exp_mask)
1914                          > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1915                                 goto ovfl;
1916                         if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1917                                 /* set to largest number */
1918                                 /* (Can't trust DBL_MAX) */
1919                                 word0(rv) = Big0;
1920                                 word1(rv) = Big1;
1921                                 }
1922                         else
1923                                 word0(rv) += P*Exp_msk1;
1924                         }
1925                 }
1926         else if (e1 < 0) {
1927                 e1 = -e1;
1928                 if ((i = e1 & 15))
1929                         dval(rv) /= tens[i];
1930                 if (e1 >>= 4) {
1931                         if (e1 >= 1 << n_bigtens)
1932                                 goto undfl;
1933 #ifdef Avoid_Underflow
1934                         if (e1 & Scale_Bit)
1935                                 scale = 2*P;
1936                         for(j = 0; e1 > 0; j++, e1 >>= 1)
1937                                 if (e1 & 1)
1938                                         dval(rv) *= tinytens[j];
1939                         if (scale && (j = 2*P + 1 - ((word0(rv) & Exp_mask)
1940                                                 >> Exp_shift)) > 0) {
1941                                 /* scaled rv is denormal; zap j low bits */
1942                                 if (j >= 32) {
1943                                         word1(rv) = 0;
1944                                         if (j >= 53)
1945                                          word0(rv) = (P+2)*Exp_msk1;
1946                                         else
1947                                          word0(rv) &= 0xffffffff << (j-32);
1948                                         }
1949                                 else
1950                                         word1(rv) &= 0xffffffff << j;
1951                                 }
1952 #else
1953                         for(j = 0; e1 > 1; j++, e1 >>= 1)
1954                                 if (e1 & 1)
1955                                         dval(rv) *= tinytens[j];
1956                         /* The last multiplication could underflow. */
1957                         dval(rv0) = dval(rv);
1958                         dval(rv) *= tinytens[j];
1959                         if (!dval(rv)) {
1960                                 dval(rv) = 2.*dval(rv0);
1961                                 dval(rv) *= tinytens[j];
1962 #endif
1963                                 if (!dval(rv)) {
1964  undfl:
1965                                         dval(rv) = 0.;
1966 #ifndef NO_ERRNO
1967                                         errno = ERANGE;
1968 #endif
1969                                         if (bd0)
1970                                                 goto retfree;
1971                                         goto ret;
1972                                         }
1973 #ifndef Avoid_Underflow
1974                                 word0(rv) = Tiny0;
1975                                 word1(rv) = Tiny1;
1976                                 /* The refinement below will clean
1977                                  * this approximation up.
1978                                  */
1979                                 }
1980 #endif
1981                         }
1982                 }
1983
1984         /* Now the hard part -- adjusting rv to the correct value.*/
1985
1986         /* Put digits into bd: true value = bd * 10^e */
1987
1988         bd0 = s2b(s0, nd0, nd, y);
1989
1990         for(;;) {
1991                 bd = Balloc(bd0->k);
1992                 Bcopy(bd, bd0);
1993                 bb = d2b(dval(rv), &bbe, &bbbits);      /* rv = bb * 2^bbe */
1994                 bs = i2b(1);
1995
1996                 if (e >= 0) {
1997                         bb2 = bb5 = 0;
1998                         bd2 = bd5 = e;
1999                         }
2000                 else {
2001                         bb2 = bb5 = -e;
2002                         bd2 = bd5 = 0;
2003                         }
2004                 if (bbe >= 0)
2005                         bb2 += bbe;
2006                 else
2007                         bd2 -= bbe;
2008                 bs2 = bb2;
2009 #ifdef Honor_FLT_ROUNDS
2010                 if (rounding != 1)
2011                         bs2++;
2012 #endif
2013 #ifdef Avoid_Underflow
2014                 j = bbe - scale;
2015                 i = j + bbbits - 1;     /* logb(rv) */
2016                 if (i < Emin)   /* denormal */
2017                         j += P - Emin;
2018                 else
2019                         j = P + 1 - bbbits;
2020 #else /*Avoid_Underflow*/
2021 #ifdef Sudden_Underflow
2022 #ifdef IBM
2023                 j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
2024 #else
2025                 j = P + 1 - bbbits;
2026 #endif
2027 #else /*Sudden_Underflow*/
2028                 j = bbe;
2029                 i = j + bbbits - 1;     /* logb(rv) */
2030                 if (i < Emin)   /* denormal */
2031                         j += P - Emin;
2032                 else
2033                         j = P + 1 - bbbits;
2034 #endif /*Sudden_Underflow*/
2035 #endif /*Avoid_Underflow*/
2036                 bb2 += j;
2037                 bd2 += j;
2038 #ifdef Avoid_Underflow
2039                 bd2 += scale;
2040 #endif
2041                 i = bb2 < bd2 ? bb2 : bd2;
2042                 if (i > bs2)
2043                         i = bs2;
2044                 if (i > 0) {
2045                         bb2 -= i;
2046                         bd2 -= i;
2047                         bs2 -= i;
2048                         }
2049                 if (bb5 > 0) {
2050                         bs = pow5mult(bs, bb5);
2051                         bb1 = mult(bs, bb);
2052                         Bfree(bb);
2053                         bb = bb1;
2054                         }
2055                 if (bb2 > 0)
2056                         bb = lshift(bb, bb2);
2057                 if (bd5 > 0)
2058                         bd = pow5mult(bd, bd5);
2059                 if (bd2 > 0)
2060                         bd = lshift(bd, bd2);
2061                 if (bs2 > 0)
2062                         bs = lshift(bs, bs2);
2063                 delta = diff(bb, bd);
2064                 dsign = delta->sign;
2065                 delta->sign = 0;
2066                 i = cmp(delta, bs);
2067 #ifdef Honor_FLT_ROUNDS
2068                 if (rounding != 1) {
2069                         if (i < 0) {
2070                                 /* Error is less than an ulp */
2071                                 if (!delta->x[0] && delta->wds <= 1) {
2072                                         /* exact */
2073 #ifdef SET_INEXACT
2074                                         inexact = 0;
2075 #endif
2076                                         break;
2077                                         }
2078                                 if (rounding) {
2079                                         if (dsign) {
2080                                                 adj = 1.;
2081                                                 goto apply_adj;
2082                                                 }
2083                                         }
2084                                 else if (!dsign) {
2085                                         adj = -1.;
2086                                         if (!word1(rv)
2087                                          && !(word0(rv) & Frac_mask)) {
2088                                                 y = word0(rv) & Exp_mask;
2089 #ifdef Avoid_Underflow
2090                                                 if (!scale || y > 2*P*Exp_msk1)
2091 #else
2092                                                 if (y)
2093 #endif
2094                                                   {
2095                                                   delta = lshift(delta,Log2P);
2096                                                   if (cmp(delta, bs) <= 0)
2097                                                         adj = -0.5;
2098                                                   }
2099                                                 }
2100  apply_adj:
2101 #ifdef Avoid_Underflow
2102                                         if (scale && (y = word0(rv) & Exp_mask)
2103                                                 <= 2*P*Exp_msk1)
2104                                           word0(adj) += (2*P+1)*Exp_msk1 - y;
2105 #else
2106 #ifdef Sudden_Underflow
2107                                         if ((word0(rv) & Exp_mask) <=
2108                                                         P*Exp_msk1) {
2109                                                 word0(rv) += P*Exp_msk1;
2110                                                 dval(rv) += adj*ulp(dval(rv));
2111                                                 word0(rv) -= P*Exp_msk1;
2112                                                 }
2113                                         else
2114 #endif /*Sudden_Underflow*/
2115 #endif /*Avoid_Underflow*/
2116                                         dval(rv) += adj*ulp(dval(rv));
2117                                         }
2118                                 break;
2119                                 }
2120                         adj = ratio(delta, bs);
2121                         if (adj < 1.)
2122                                 adj = 1.;
2123                         if (adj <= 0x7ffffffe) {
2124                                 /* adj = rounding ? ceil(adj) : floor(adj); */
2125                                 y = adj;
2126                                 if (y != adj) {
2127                                         if (!((rounding>>1) ^ dsign))
2128                                                 y++;
2129                                         adj = y;
2130                                         }
2131                                 }
2132 #ifdef Avoid_Underflow
2133                         if (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2134                                 word0(adj) += (2*P+1)*Exp_msk1 - y;
2135 #else
2136 #ifdef Sudden_Underflow
2137                         if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2138                                 word0(rv) += P*Exp_msk1;
2139                                 adj *= ulp(dval(rv));
2140                                 if (dsign)
2141                                         dval(rv) += adj;
2142                                 else
2143                                         dval(rv) -= adj;
2144                                 word0(rv) -= P*Exp_msk1;
2145                                 goto cont;
2146                                 }
2147 #endif /*Sudden_Underflow*/
2148 #endif /*Avoid_Underflow*/
2149                         adj *= ulp(dval(rv));
2150                         if (dsign)
2151                                 dval(rv) += adj;
2152                         else
2153                                 dval(rv) -= adj;
2154                         goto cont;
2155                         }
2156 #endif /*Honor_FLT_ROUNDS*/
2157
2158                 if (i < 0) {
2159                         /* Error is less than half an ulp -- check for
2160                          * special case of mantissa a power of two.
2161                          */
2162                         if (dsign || word1(rv) || word0(rv) & Bndry_mask
2163 #ifdef IEEE_Arith
2164 #ifdef Avoid_Underflow
2165                          || (word0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1
2166 #else
2167                          || (word0(rv) & Exp_mask) <= Exp_msk1
2168 #endif
2169 #endif
2170                                 ) {
2171 #ifdef SET_INEXACT
2172                                 if (!delta->x[0] && delta->wds <= 1)
2173                                         inexact = 0;
2174 #endif
2175                                 break;
2176                                 }
2177                         if (!delta->x[0] && delta->wds <= 1) {
2178                                 /* exact result */
2179 #ifdef SET_INEXACT
2180                                 inexact = 0;
2181 #endif
2182                                 break;
2183                                 }
2184                         delta = lshift(delta,Log2P);
2185                         if (cmp(delta, bs) > 0)
2186                                 goto drop_down;
2187                         break;
2188                         }
2189                 if (i == 0) {
2190                         /* exactly half-way between */
2191                         if (dsign) {
2192                                 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
2193                                  &&  word1(rv) == (
2194 #ifdef Avoid_Underflow
2195                         (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2196                 ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
2197 #endif
2198                                                    0xffffffff)) {
2199                                         /*boundary case -- increment exponent*/
2200                                         word0(rv) = (word0(rv) & Exp_mask)
2201                                                 + Exp_msk1
2202 #ifdef IBM
2203                                                 | Exp_msk1 >> 4
2204 #endif
2205                                                 ;
2206                                         word1(rv) = 0;
2207 #ifdef Avoid_Underflow
2208                                         dsign = 0;
2209 #endif
2210                                         break;
2211                                         }
2212                                 }
2213                         else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
2214  drop_down:
2215                                 /* boundary case -- decrement exponent */
2216 #ifdef Sudden_Underflow /*{{*/
2217                                 L = word0(rv) & Exp_mask;
2218 #ifdef IBM
2219                                 if (L <  Exp_msk1)
2220 #else
2221 #ifdef Avoid_Underflow
2222                                 if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
2223 #else
2224                                 if (L <= Exp_msk1)
2225 #endif /*Avoid_Underflow*/
2226 #endif /*IBM*/
2227                                         goto undfl;
2228                                 L -= Exp_msk1;
2229 #else /*Sudden_Underflow}{*/
2230 #ifdef Avoid_Underflow
2231                                 if (scale) {
2232                                         L = word0(rv) & Exp_mask;
2233                                         if (L <= (2*P+1)*Exp_msk1) {
2234                                                 if (L > (P+2)*Exp_msk1)
2235                                                         /* round even ==> */
2236                                                         /* accept rv */
2237                                                         break;
2238                                                 /* rv = smallest denormal */
2239                                                 goto undfl;
2240                                                 }
2241                                         }
2242 #endif /*Avoid_Underflow*/
2243                                 L = (word0(rv) & Exp_mask) - Exp_msk1;
2244 #endif /*Sudden_Underflow}}*/
2245                                 word0(rv) = L | Bndry_mask1;
2246                                 word1(rv) = 0xffffffff;
2247 #ifdef IBM
2248                                 goto cont;
2249 #else
2250                                 break;
2251 #endif
2252                                 }
2253 #ifndef ROUND_BIASED
2254                         if (!(word1(rv) & LSB))
2255                                 break;
2256 #endif
2257                         if (dsign)
2258                                 dval(rv) += ulp(dval(rv));
2259 #ifndef ROUND_BIASED
2260                         else {
2261                                 dval(rv) -= ulp(dval(rv));
2262 #ifndef Sudden_Underflow
2263                                 if (!dval(rv))
2264                                         goto undfl;
2265 #endif
2266                                 }
2267 #ifdef Avoid_Underflow
2268                         dsign = 1 - dsign;
2269 #endif
2270 #endif
2271                         break;
2272                         }
2273                 if ((aadj = ratio(delta, bs)) <= 2.) {
2274                         if (dsign)
2275                                 aadj = aadj1 = 1.;
2276                         else if (word1(rv) || word0(rv) & Bndry_mask) {
2277 #ifndef Sudden_Underflow
2278                                 if (word1(rv) == Tiny1 && !word0(rv))
2279                                         goto undfl;
2280 #endif
2281                                 aadj = 1.;
2282                                 aadj1 = -1.;
2283                                 }
2284                         else {
2285                                 /* special case -- power of FLT_RADIX to be */
2286                                 /* rounded down... */
2287
2288                                 if (aadj < 2./FLT_RADIX)
2289                                         aadj = 1./FLT_RADIX;
2290                                 else
2291                                         aadj *= 0.5;
2292                                 aadj1 = -aadj;
2293                                 }
2294                         }
2295                 else {
2296                         aadj *= 0.5;
2297                         aadj1 = dsign ? aadj : -aadj;
2298 #ifdef Check_FLT_ROUNDS
2299                         switch(Rounding) {
2300                                 case 2: /* towards +infinity */
2301                                         aadj1 -= 0.5;
2302                                         break;
2303                                 case 0: /* towards 0 */
2304                                 case 3: /* towards -infinity */
2305                                         aadj1 += 0.5;
2306                                 }
2307 #else
2308                         if (Flt_Rounds == 0)
2309                                 aadj1 += 0.5;
2310 #endif /*Check_FLT_ROUNDS*/
2311                         }
2312                 y = word0(rv) & Exp_mask;
2313
2314                 /* Check for overflow */
2315
2316                 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2317                         dval(rv0) = dval(rv);
2318                         word0(rv) -= P*Exp_msk1;
2319                         adj = aadj1 * ulp(dval(rv));
2320                         dval(rv) += adj;
2321                         if ((word0(rv) & Exp_mask) >=
2322                                         Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2323                                 if (word0(rv0) == Big0 && word1(rv0) == Big1)
2324                                         goto ovfl;
2325                                 word0(rv) = Big0;
2326                                 word1(rv) = Big1;
2327                                 goto cont;
2328                                 }
2329                         else
2330                                 word0(rv) += P*Exp_msk1;
2331                         }
2332                 else {
2333 #ifdef Avoid_Underflow
2334                         if (scale && y <= 2*P*Exp_msk1) {
2335                                 if (aadj <= 0x7fffffff) {
2336                                         if ((z = aadj) <= 0)
2337                                                 z = 1;
2338                                         aadj = z;
2339                                         aadj1 = dsign ? aadj : -aadj;
2340                                         }
2341                                 word0(aadj1) += (2*P+1)*Exp_msk1 - y;
2342                                 }
2343                         adj = aadj1 * ulp(dval(rv));
2344                         dval(rv) += adj;
2345 #else
2346 #ifdef Sudden_Underflow
2347                         if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2348                                 dval(rv0) = dval(rv);
2349                                 word0(rv) += P*Exp_msk1;
2350                                 adj = aadj1 * ulp(dval(rv));
2351                                 dval(rv) += adj;
2352 #ifdef IBM
2353                                 if ((word0(rv) & Exp_mask) <  P*Exp_msk1)
2354 #else
2355                                 if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
2356 #endif
2357                                         {
2358                                         if (word0(rv0) == Tiny0
2359                                          && word1(rv0) == Tiny1)
2360                                                 goto undfl;
2361                                         word0(rv) = Tiny0;
2362                                         word1(rv) = Tiny1;
2363                                         goto cont;
2364                                         }
2365                                 else
2366                                         word0(rv) -= P*Exp_msk1;
2367                                 }
2368                         else {
2369                                 adj = aadj1 * ulp(dval(rv));
2370                                 dval(rv) += adj;
2371                                 }
2372 #else /*Sudden_Underflow*/
2373                         /* Compute adj so that the IEEE rounding rules will
2374                          * correctly round rv + adj in some half-way cases.
2375                          * If rv * ulp(rv) is denormalized (i.e.,
2376                          * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
2377                          * trouble from bits lost to denormalization;
2378                          * example: 1.2e-307 .
2379                          */
2380                         if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
2381                                 aadj1 = (double)(int)(aadj + 0.5);
2382                                 if (!dsign)
2383                                         aadj1 = -aadj1;
2384                                 }
2385                         adj = aadj1 * ulp(dval(rv));
2386                         dval(rv) += adj;
2387 #endif /*Sudden_Underflow*/
2388 #endif /*Avoid_Underflow*/
2389                         }
2390                 z = word0(rv) & Exp_mask;
2391 #ifndef SET_INEXACT
2392 #ifdef Avoid_Underflow
2393                 if (!scale)
2394 #endif
2395                 if (y == z) {
2396                         /* Can we stop now? */
2397                         L = (Long)aadj;
2398                         aadj -= L;
2399                         /* The tolerances below are conservative. */
2400                         if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
2401                                 if (aadj < .4999999 || aadj > .5000001)
2402                                         break;
2403                                 }
2404                         else if (aadj < .4999999/FLT_RADIX)
2405                                 break;
2406                         }
2407 #endif
2408  cont:
2409                 Bfree(bb);
2410                 Bfree(bd);
2411                 Bfree(bs);
2412                 Bfree(delta);
2413                 }
2414 #ifdef SET_INEXACT
2415         if (inexact) {
2416                 if (!oldinexact) {
2417                         word0(rv0) = Exp_1 + (70 << Exp_shift);
2418                         word1(rv0) = 0;
2419                         dval(rv0) += 1.;
2420                         }
2421                 }
2422         else if (!oldinexact)
2423                 clear_inexact();
2424 #endif
2425 #ifdef Avoid_Underflow
2426         if (scale) {
2427                 word0(rv0) = Exp_1 - 2*P*Exp_msk1;
2428                 word1(rv0) = 0;
2429                 dval(rv) *= dval(rv0);
2430 #ifndef NO_ERRNO
2431                 /* try to avoid the bug of testing an 8087 register value */
2432                 if (word0(rv) == 0 && word1(rv) == 0)
2433                         errno = ERANGE;
2434 #endif
2435                 }
2436 #endif /* Avoid_Underflow */
2437 #ifdef SET_INEXACT
2438         if (inexact && !(word0(rv) & Exp_mask)) {
2439                 /* set underflow bit */
2440                 dval(rv0) = 1e-300;
2441                 dval(rv0) *= dval(rv0);
2442                 }
2443 #endif
2444  retfree:
2445         Bfree(bb);
2446         Bfree(bd);
2447         Bfree(bs);
2448         Bfree(bd0);
2449         Bfree(delta);
2450  ret:
2451         if (se)
2452                 *se = (char *)s;
2453         return sign ? -dval(rv) : dval(rv);
2454         }
2455
2456 #if 0
2457  static int
2458 quorem
2459 #ifdef KR_headers
2460         (b, S) Bigint *b, *S;
2461 #else
2462         (Bigint *b, Bigint *S)
2463 #endif
2464 {
2465         int n;
2466         ULong *bx, *bxe, q, *sx, *sxe;
2467 #ifdef ULLong
2468         ULLong borrow, carry, y, ys;
2469 #else
2470         ULong borrow, carry, y, ys;
2471 #ifdef Pack_32
2472         ULong si, z, zs;
2473 #endif
2474 #endif
2475
2476         n = S->wds;
2477 #ifdef DEBUG
2478         /*debug*/ if (b->wds > n)
2479         /*debug*/       Bug("oversize b in quorem");
2480 #endif
2481         if (b->wds < n)
2482                 return 0;
2483         sx = S->x;
2484         sxe = sx + --n;
2485         bx = b->x;
2486         bxe = bx + n;
2487         q = *bxe / (*sxe + 1);  /* ensure q <= true quotient */
2488 #ifdef DEBUG
2489         /*debug*/ if (q > 9)
2490         /*debug*/       Bug("oversized quotient in quorem");
2491 #endif
2492         if (q) {
2493                 borrow = 0;
2494                 carry = 0;
2495                 do {
2496 #ifdef ULLong
2497                         ys = *sx++ * (ULLong)q + carry;
2498                         carry = ys >> 32;
2499                         y = *bx - (ys & FFFFFFFF) - borrow;
2500                         borrow = y >> 32 & (ULong)1;
2501                         *bx++ = y & FFFFFFFF;
2502 #else
2503 #ifdef Pack_32
2504                         si = *sx++;
2505                         ys = (si & 0xffff) * q + carry;
2506                         zs = (si >> 16) * q + (ys >> 16);
2507                         carry = zs >> 16;
2508                         y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
2509                         borrow = (y & 0x10000) >> 16;
2510                         z = (*bx >> 16) - (zs & 0xffff) - borrow;
2511                         borrow = (z & 0x10000) >> 16;
2512                         Storeinc(bx, z, y);
2513 #else
2514                         ys = *sx++ * q + carry;
2515                         carry = ys >> 16;
2516                         y = *bx - (ys & 0xffff) - borrow;
2517                         borrow = (y & 0x10000) >> 16;
2518                         *bx++ = y & 0xffff;
2519 #endif
2520 #endif
2521                         }
2522                         while(sx <= sxe);
2523                 if (!*bxe) {
2524                         bx = b->x;
2525                         while(--bxe > bx && !*bxe)
2526                                 --n;
2527                         b->wds = n;
2528                         }
2529                 }
2530         if (cmp(b, S) >= 0) {
2531                 q++;
2532                 borrow = 0;
2533                 carry = 0;
2534                 bx = b->x;
2535                 sx = S->x;
2536                 do {
2537 #ifdef ULLong
2538                         ys = *sx++ + carry;
2539                         carry = ys >> 32;
2540                         y = *bx - (ys & FFFFFFFF) - borrow;
2541                         borrow = y >> 32 & (ULong)1;
2542                         *bx++ = y & FFFFFFFF;
2543 #else
2544 #ifdef Pack_32
2545                         si = *sx++;
2546                         ys = (si & 0xffff) + carry;
2547                         zs = (si >> 16) + (ys >> 16);
2548                         carry = zs >> 16;
2549                         y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
2550                         borrow = (y & 0x10000) >> 16;
2551                         z = (*bx >> 16) - (zs & 0xffff) - borrow;
2552                         borrow = (z & 0x10000) >> 16;
2553                         Storeinc(bx, z, y);
2554 #else
2555                         ys = *sx++ + carry;
2556                         carry = ys >> 16;
2557                         y = *bx - (ys & 0xffff) - borrow;
2558                         borrow = (y & 0x10000) >> 16;
2559                         *bx++ = y & 0xffff;
2560 #endif
2561 #endif
2562                         }
2563                         while(sx <= sxe);
2564                 bx = b->x;
2565                 bxe = bx + n;
2566                 if (!*bxe) {
2567                         while(--bxe > bx && !*bxe)
2568                                 --n;
2569                         b->wds = n;
2570                         }
2571                 }
2572         return q;
2573         }
2574 #endif
2575
2576 #ifndef MULTIPLE_THREADS
2577  static char *dtoa_result;
2578 #endif
2579
2580 #if 0
2581  static char *
2582 #ifdef KR_headers
2583 rv_alloc(i) int i;
2584 #else
2585 rv_alloc(int i)
2586 #endif
2587 {
2588         int j, k, *r;
2589
2590         j = sizeof(ULong);
2591         for(k = 0;
2592                 sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= i;
2593                 j <<= 1)
2594                         k++;
2595         r = (int*)Balloc(k);
2596         *r = k;
2597         return
2598 #ifndef MULTIPLE_THREADS
2599         dtoa_result =
2600 #endif
2601                 (char *)(r+1);
2602         }
2603
2604  static char *
2605 #ifdef KR_headers
2606 nrv_alloc(s, rve, n) char *s, **rve; int n;
2607 #else
2608 nrv_alloc(char *s, char **rve, int n)
2609 #endif
2610 {
2611         char *rv, *t;
2612
2613         t = rv = rv_alloc(n);
2614         while((*t = *s++)) t++;
2615         if (rve)
2616                 *rve = t;
2617         return rv;
2618         }
2619
2620 /* freedtoa(s) must be used to free values s returned by dtoa
2621  * when MULTIPLE_THREADS is #defined.  It should be used in all cases,
2622  * but for consistency with earlier versions of dtoa, it is optional
2623  * when MULTIPLE_THREADS is not defined.
2624  */
2625
2626 static void freedtoa (char *s);
2627
2628 static void
2629 #ifdef KR_headers
2630 freedtoa(s) char *s;
2631 #else
2632 freedtoa(char *s)
2633 #endif
2634 {
2635         Bigint *b = (Bigint *)((int *)s - 1);
2636         b->maxwds = 1 << (b->k = *(int*)b);
2637         Bfree(b);
2638 #ifndef MULTIPLE_THREADS
2639         if (s == dtoa_result)
2640                 dtoa_result = 0;
2641 #endif
2642         }
2643
2644 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
2645  *
2646  * Inspired by "How to Print Floating-Point Numbers Accurately" by
2647  * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
2648  *
2649  * Modifications:
2650  *      1. Rather than iterating, we use a simple numeric overestimate
2651  *         to determine k = floor(log10(d)).  We scale relevant
2652  *         quantities using O(log2(k)) rather than O(k) multiplications.
2653  *      2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
2654  *         try to generate digits strictly left to right.  Instead, we
2655  *         compute with fewer bits and propagate the carry if necessary
2656  *         when rounding the final digit up.  This is often faster.
2657  *      3. Under the assumption that input will be rounded nearest,
2658  *         mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
2659  *         That is, we allow equality in stopping tests when the
2660  *         round-nearest rule will give the same floating-point value
2661  *         as would satisfaction of the stopping test with strict
2662  *         inequality.
2663  *      4. We remove common factors of powers of 2 from relevant
2664  *         quantities.
2665  *      5. When converting floating-point integers less than 1e16,
2666  *         we use floating-point arithmetic rather than resorting
2667  *         to multiple-precision integers.
2668  *      6. When asked to produce fewer than 15 digits, we first try
2669  *         to get by with floating-point arithmetic; we resort to
2670  *         multiple-precision integer arithmetic only if we cannot
2671  *         guarantee that the floating-point calculation has given
2672  *         the correctly rounded result.  For k requested digits and
2673  *         "uniformly" distributed input, the probability is
2674  *         something like 10^(k-15) that we must resort to the Long
2675  *         calculation.
2676  */
2677
2678  char *
2679 dtoa
2680 #ifdef KR_headers
2681         (d, mode, ndigits, decpt, sign, rve)
2682         double d; int mode, ndigits, *decpt, *sign; char **rve;
2683 #else
2684         (double d, int mode, int ndigits, int *decpt, int *sign, char **rve)
2685 #endif
2686 {
2687  /*     Arguments ndigits, decpt, sign are similar to those
2688         of ecvt and fcvt; trailing zeros are suppressed from
2689         the returned string.  If not null, *rve is set to point
2690         to the end of the return value.  If d is +-Infinity or NaN,
2691         then *decpt is set to 9999.
2692
2693         mode:
2694                 0 ==> shortest string that yields d when read in
2695                         and rounded to nearest.
2696                 1 ==> like 0, but with Steele & White stopping rule;
2697                         e.g. with IEEE P754 arithmetic , mode 0 gives
2698                         1e23 whereas mode 1 gives 9.999999999999999e22.
2699                 2 ==> max(1,ndigits) significant digits.  This gives a
2700                         return value similar to that of ecvt, except
2701                         that trailing zeros are suppressed.
2702                 3 ==> through ndigits past the decimal point.  This
2703                         gives a return value similar to that from fcvt,
2704                         except that trailing zeros are suppressed, and
2705                         ndigits can be negative.
2706                 4,5 ==> similar to 2 and 3, respectively, but (in
2707                         round-nearest mode) with the tests of mode 0 to
2708                         possibly return a shorter string that rounds to d.
2709                         With IEEE arithmetic and compilation with
2710                         -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
2711                         as modes 2 and 3 when FLT_ROUNDS != 1.
2712                 6-9 ==> Debugging modes similar to mode - 4:  don't try
2713                         fast floating-point estimate (if applicable).
2714
2715                 Values of mode other than 0-9 are treated as mode 0.
2716
2717                 Sufficient space is allocated to the return value
2718                 to hold the suppressed trailing zeros.
2719         */
2720
2721         int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2722                 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2723                 spec_case, try_quick;
2724         Long L;
2725 #ifndef Sudden_Underflow
2726         int denorm;
2727         ULong x;
2728 #endif
2729         Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2730         double d2, ds, eps;
2731         char *s, *s0;
2732 #ifdef Honor_FLT_ROUNDS
2733         int rounding;
2734 #endif
2735 #ifdef SET_INEXACT
2736         int inexact, oldinexact;
2737 #endif
2738
2739 #ifndef MULTIPLE_THREADS
2740         if (dtoa_result) {
2741                 freedtoa(dtoa_result);
2742                 dtoa_result = 0;
2743                 }
2744 #endif
2745
2746         if (word0(d) & Sign_bit) {
2747                 /* set sign for everything, including 0's and NaNs */
2748                 *sign = 1;
2749                 word0(d) &= ~Sign_bit;  /* clear sign bit */
2750                 }
2751         else
2752                 *sign = 0;
2753
2754 #if defined(IEEE_Arith) + defined(VAX)
2755 #ifdef IEEE_Arith
2756         if ((word0(d) & Exp_mask) == Exp_mask)
2757 #else
2758         if (word0(d)  == 0x8000)
2759 #endif
2760                 {
2761                 /* Infinity or NaN */
2762                 *decpt = 9999;
2763 #ifdef IEEE_Arith
2764                 if (!word1(d) && !(word0(d) & 0xfffff))
2765                         return nrv_alloc("Infinity", rve, 8);
2766 #endif
2767                 return nrv_alloc("NaN", rve, 3);
2768                 }
2769 #endif
2770 #ifdef IBM
2771         dval(d) += 0; /* normalize */
2772 #endif
2773         if (!dval(d)) {
2774                 *decpt = 1;
2775                 return nrv_alloc("0", rve, 1);
2776                 }
2777
2778 #ifdef SET_INEXACT
2779         try_quick = oldinexact = get_inexact();
2780         inexact = 1;
2781 #endif
2782 #ifdef Honor_FLT_ROUNDS
2783         if ((rounding = Flt_Rounds) >= 2) {
2784                 if (*sign)
2785                         rounding = rounding == 2 ? 0 : 2;
2786                 else
2787                         if (rounding != 2)
2788                                 rounding = 0;
2789                 }
2790 #endif
2791
2792         b = d2b(dval(d), &be, &bbits);
2793 #ifdef Sudden_Underflow
2794         i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
2795 #else
2796         if (i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))) {
2797 #endif
2798                 dval(d2) = dval(d);
2799                 word0(d2) &= Frac_mask1;
2800                 word0(d2) |= Exp_11;
2801 #ifdef IBM
2802                 if (j = 11 - hi0bits(word0(d2) & Frac_mask))
2803                         dval(d2) /= 1 << j;
2804 #endif
2805
2806                 /* log(x)       ~=~ log(1.5) + (x-1.5)/1.5
2807                  * log10(x)      =  log(x) / log(10)
2808                  *              ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
2809                  * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
2810                  *
2811                  * This suggests computing an approximation k to log10(d) by
2812                  *
2813                  * k = (i - Bias)*0.301029995663981
2814                  *      + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
2815                  *
2816                  * We want k to be too large rather than too small.
2817                  * The error in the first-order Taylor series approximation
2818                  * is in our favor, so we just round up the constant enough
2819                  * to compensate for any error in the multiplication of
2820                  * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
2821                  * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
2822                  * adding 1e-13 to the constant term more than suffices.
2823                  * Hence we adjust the constant term to 0.1760912590558.
2824                  * (We could get a more accurate k by invoking log10,
2825                  *  but this is probably not worthwhile.)
2826                  */
2827
2828                 i -= Bias;
2829 #ifdef IBM
2830                 i <<= 2;
2831                 i += j;
2832 #endif
2833 #ifndef Sudden_Underflow
2834                 denorm = 0;
2835                 }
2836         else {
2837                 /* d is denormalized */
2838
2839                 i = bbits + be + (Bias + (P-1) - 1);
2840                 x = i > 32  ? word0(d) << 64 - i | word1(d) >> i - 32
2841                             : word1(d) << 32 - i;
2842                 dval(d2) = x;
2843                 word0(d2) -= 31*Exp_msk1; /* adjust exponent */
2844                 i -= (Bias + (P-1) - 1) + 1;
2845                 denorm = 1;
2846                 }
2847 #endif
2848         ds = (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
2849         k = (int)ds;
2850         if (ds < 0. && ds != k)
2851                 k--;    /* want k = floor(ds) */
2852         k_check = 1;
2853         if (k >= 0 && k <= Ten_pmax) {
2854                 if (dval(d) < tens[k])
2855                         k--;
2856                 k_check = 0;
2857                 }
2858         j = bbits - i - 1;
2859         if (j >= 0) {
2860                 b2 = 0;
2861                 s2 = j;
2862                 }
2863         else {
2864                 b2 = -j;
2865                 s2 = 0;
2866                 }
2867         if (k >= 0) {
2868                 b5 = 0;
2869                 s5 = k;
2870                 s2 += k;
2871                 }
2872         else {
2873                 b2 -= k;
2874                 b5 = -k;
2875                 s5 = 0;
2876                 }
2877         if (mode < 0 || mode > 9)
2878                 mode = 0;
2879
2880 #ifndef SET_INEXACT
2881 #ifdef Check_FLT_ROUNDS
2882         try_quick = Rounding == 1;
2883 #else
2884         try_quick = 1;
2885 #endif
2886 #endif /*SET_INEXACT*/
2887
2888         if (mode > 5) {
2889                 mode -= 4;
2890                 try_quick = 0;
2891                 }
2892         leftright = 1;
2893         switch(mode) {
2894                 case 0:
2895                 case 1:
2896                         ilim = ilim1 = -1;
2897                         i = 18;
2898                         ndigits = 0;
2899                         break;
2900                 case 2:
2901                         leftright = 0;
2902                         /* no break */
2903                 case 4:
2904                         if (ndigits <= 0)
2905                                 ndigits = 1;
2906                         ilim = ilim1 = i = ndigits;
2907                         break;
2908                 case 3:
2909                         leftright = 0;
2910                         /* no break */
2911                 case 5:
2912                         i = ndigits + k + 1;
2913                         ilim = i;
2914                         ilim1 = i - 1;
2915                         if (i <= 0)
2916                                 i = 1;
2917                 }
2918         s = s0 = rv_alloc(i);
2919
2920 #ifdef Honor_FLT_ROUNDS
2921         if (mode > 1 && rounding != 1)
2922                 leftright = 0;
2923 #endif
2924
2925         if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2926
2927                 /* Try to get by with floating-point arithmetic. */
2928
2929                 i = 0;
2930                 dval(d2) = dval(d);
2931                 k0 = k;
2932                 ilim0 = ilim;
2933                 ieps = 2; /* conservative */
2934                 if (k > 0) {
2935                         ds = tens[k&0xf];
2936                         j = k >> 4;
2937                         if (j & Bletch) {
2938                                 /* prevent overflows */
2939                                 j &= Bletch - 1;
2940                                 dval(d) /= bigtens[n_bigtens-1];
2941                                 ieps++;
2942                                 }
2943                         for(; j; j >>= 1, i++)
2944                                 if (j & 1) {
2945                                         ieps++;
2946                                         ds *= bigtens[i];
2947                                         }
2948                         dval(d) /= ds;
2949                         }
2950                 else if (j1 = -k) {
2951                         dval(d) *= tens[j1 & 0xf];
2952                         for(j = j1 >> 4; j; j >>= 1, i++)
2953                                 if (j & 1) {
2954                                         ieps++;
2955                                         dval(d) *= bigtens[i];
2956                                         }
2957                         }
2958                 if (k_check && dval(d) < 1. && ilim > 0) {
2959                         if (ilim1 <= 0)
2960                                 goto fast_failed;
2961                         ilim = ilim1;
2962                         k--;
2963                         dval(d) *= 10.;
2964                         ieps++;
2965                         }
2966                 dval(eps) = ieps*dval(d) + 7.;
2967                 word0(eps) -= (P-1)*Exp_msk1;
2968                 if (ilim == 0) {
2969                         S = mhi = 0;
2970                         dval(d) -= 5.;
2971                         if (dval(d) > dval(eps))
2972                                 goto one_digit;
2973                         if (dval(d) < -dval(eps))
2974                                 goto no_digits;
2975                         goto fast_failed;
2976                         }
2977 #ifndef No_leftright
2978                 if (leftright) {
2979                         /* Use Steele & White method of only
2980                          * generating digits needed.
2981                          */
2982                         dval(eps) = 0.5/tens[ilim-1] - dval(eps);
2983                         for(i = 0;;) {
2984                                 L = dval(d);
2985                                 dval(d) -= L;
2986                                 *s++ = '0' + (int)L;
2987                                 if (dval(d) < dval(eps))
2988                                         goto ret1;
2989                                 if (1. - dval(d) < dval(eps))
2990                                         goto bump_up;
2991                                 if (++i >= ilim)
2992                                         break;
2993                                 dval(eps) *= 10.;
2994                                 dval(d) *= 10.;
2995                                 }
2996                         }
2997                 else {
2998 #endif
2999                         /* Generate ilim digits, then fix them up. */
3000                         dval(eps) *= tens[ilim-1];
3001                         for(i = 1;; i++, dval(d) *= 10.) {
3002                                 L = (Long)(dval(d));
3003                                 if (!(dval(d) -= L))
3004                                         ilim = i;
3005                                 *s++ = '0' + (int)L;
3006                                 if (i == ilim) {
3007                                         if (dval(d) > 0.5 + dval(eps))
3008                                                 goto bump_up;
3009                                         else if (dval(d) < 0.5 - dval(eps)) {
3010                                                 while(*--s == '0');
3011                                                 s++;
3012                                                 goto ret1;
3013                                                 }
3014                                         break;
3015                                         }
3016                                 }
3017 #ifndef No_leftright
3018                         }
3019 #endif
3020  fast_failed:
3021                 s = s0;
3022                 dval(d) = dval(d2);
3023                 k = k0;
3024                 ilim = ilim0;
3025                 }
3026
3027         /* Do we have a "small" integer? */
3028
3029         if (be >= 0 && k <= Int_max) {
3030                 /* Yes. */
3031                 ds = tens[k];
3032                 if (ndigits < 0 && ilim <= 0) {
3033                         S = mhi = 0;
3034                         if (ilim < 0 || dval(d) <= 5*ds)
3035                                 goto no_digits;
3036                         goto one_digit;
3037                         }
3038                 for(i = 1;; i++, dval(d) *= 10.) {
3039                         L = (Long)(dval(d) / ds);
3040                         dval(d) -= L*ds;
3041 #ifdef Check_FLT_ROUNDS
3042                         /* If FLT_ROUNDS == 2, L will usually be high by 1 */
3043                         if (dval(d) < 0) {
3044                                 L--;
3045                                 dval(d) += ds;
3046                                 }
3047 #endif
3048                         *s++ = '0' + (int)L;
3049                         if (!dval(d)) {
3050 #ifdef SET_INEXACT
3051                                 inexact = 0;
3052 #endif
3053                                 break;
3054                                 }
3055                         if (i == ilim) {
3056 #ifdef Honor_FLT_ROUNDS
3057                                 if (mode > 1)
3058                                 switch(rounding) {
3059                                   case 0: goto ret1;
3060                                   case 2: goto bump_up;
3061                                   }
3062 #endif
3063                                 dval(d) += dval(d);
3064                                 if (dval(d) > ds || dval(d) == ds && L & 1) {
3065  bump_up:
3066                                         while(*--s == '9')
3067                                                 if (s == s0) {
3068                                                         k++;
3069                                                         *s = '0';
3070                                                         break;
3071                                                         }
3072                                         ++*s++;
3073                                         }
3074                                 break;
3075                                 }
3076                         }
3077                 goto ret1;
3078                 }
3079
3080         m2 = b2;
3081         m5 = b5;
3082         mhi = mlo = 0;
3083         if (leftright) {
3084                 i =
3085 #ifndef Sudden_Underflow
3086                         denorm ? be + (Bias + (P-1) - 1 + 1) :
3087 #endif
3088 #ifdef IBM
3089                         1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
3090 #else
3091                         1 + P - bbits;
3092 #endif
3093                 b2 += i;
3094                 s2 += i;
3095                 mhi = i2b(1);
3096                 }
3097         if (m2 > 0 && s2 > 0) {
3098                 i = m2 < s2 ? m2 : s2;
3099                 b2 -= i;
3100                 m2 -= i;
3101                 s2 -= i;
3102                 }
3103         if (b5 > 0) {
3104                 if (leftright) {
3105                         if (m5 > 0) {
3106                                 mhi = pow5mult(mhi, m5);
3107                                 b1 = mult(mhi, b);
3108                                 Bfree(b);
3109                                 b = b1;
3110                                 }
3111                         if (j = b5 - m5)
3112                                 b = pow5mult(b, j);
3113                         }
3114                 else
3115                         b = pow5mult(b, b5);
3116                 }
3117         S = i2b(1);
3118         if (s5 > 0)
3119                 S = pow5mult(S, s5);
3120
3121         /* Check for special case that d is a normalized power of 2. */
3122
3123         spec_case = 0;
3124         if ((mode < 2 || leftright)
3125 #ifdef Honor_FLT_ROUNDS
3126                         && rounding == 1
3127 #endif
3128                                 ) {
3129                 if (!word1(d) && !(word0(d) & Bndry_mask)
3130 #ifndef Sudden_Underflow
3131                  && word0(d) & (Exp_mask & ~Exp_msk1)
3132 #endif
3133                                 ) {
3134                         /* The special case */
3135                         b2 += Log2P;
3136                         s2 += Log2P;
3137                         spec_case = 1;
3138                         }
3139                 }
3140
3141         /* Arrange for convenient computation of quotients:
3142          * shift left if necessary so divisor has 4 leading 0 bits.
3143          *
3144          * Perhaps we should just compute leading 28 bits of S once
3145          * and for all and pass them and a shift to quorem, so it
3146          * can do shifts and ors to compute the numerator for q.
3147          */
3148 #ifdef Pack_32
3149         if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f)
3150                 i = 32 - i;
3151 #else
3152         if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf)
3153                 i = 16 - i;
3154 #endif
3155         if (i > 4) {
3156                 i -= 4;
3157                 b2 += i;
3158                 m2 += i;
3159                 s2 += i;
3160                 }
3161         else if (i < 4) {
3162                 i += 28;
3163                 b2 += i;
3164                 m2 += i;
3165                 s2 += i;
3166                 }
3167         if (b2 > 0)
3168                 b = lshift(b, b2);
3169         if (s2 > 0)
3170                 S = lshift(S, s2);
3171         if (k_check) {
3172                 if (cmp(b,S) < 0) {
3173                         k--;
3174                         b = multadd(b, 10, 0);  /* we botched the k estimate */
3175                         if (leftright)
3176                                 mhi = multadd(mhi, 10, 0);
3177                         ilim = ilim1;
3178                         }
3179                 }
3180         if (ilim <= 0 && (mode == 3 || mode == 5)) {
3181                 if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
3182                         /* no digits, fcvt style */
3183  no_digits:
3184                         k = -1 - ndigits;
3185                         goto ret;
3186                         }
3187  one_digit:
3188                 *s++ = '1';
3189                 k++;
3190                 goto ret;
3191                 }
3192         if (leftright) {
3193                 if (m2 > 0)
3194                         mhi = lshift(mhi, m2);
3195
3196                 /* Compute mlo -- check for special case
3197                  * that d is a normalized power of 2.
3198                  */
3199
3200                 mlo = mhi;
3201                 if (spec_case) {
3202                         mhi = Balloc(mhi->k);
3203                         Bcopy(mhi, mlo);
3204                         mhi = lshift(mhi, Log2P);
3205                         }
3206
3207                 for(i = 1;;i++) {
3208                         dig = quorem(b,S) + '0';
3209                         /* Do we yet have the shortest decimal string
3210                          * that will round to d?
3211                          */
3212                         j = cmp(b, mlo);
3213                         delta = diff(S, mhi);
3214                         j1 = delta->sign ? 1 : cmp(b, delta);
3215                         Bfree(delta);
3216 #ifndef ROUND_BIASED
3217                         if (j1 == 0 && mode != 1 && !(word1(d) & 1)
3218 #ifdef Honor_FLT_ROUNDS
3219                                 && rounding >= 1
3220 #endif
3221                                                                    ) {
3222                                 if (dig == '9')
3223                                         goto round_9_up;
3224                                 if (j > 0)
3225                                         dig++;
3226 #ifdef SET_INEXACT
3227                                 else if (!b->x[0] && b->wds <= 1)
3228                                         inexact = 0;
3229 #endif
3230                                 *s++ = dig;
3231                                 goto ret;
3232                                 }
3233 #endif
3234                         if (j < 0 || j == 0 && mode != 1
3235 #ifndef ROUND_BIASED
3236                                                         && !(word1(d) & 1)
3237 #endif
3238                                         ) {
3239                                 if (!b->x[0] && b->wds <= 1) {
3240 #ifdef SET_INEXACT
3241                                         inexact = 0;
3242 #endif
3243                                         goto accept_dig;
3244                                         }
3245 #ifdef Honor_FLT_ROUNDS
3246                                 if (mode > 1)
3247                                  switch(rounding) {
3248                                   case 0: goto accept_dig;
3249                                   case 2: goto keep_dig;
3250                                   }
3251 #endif /*Honor_FLT_ROUNDS*/
3252                                 if (j1 > 0) {
3253                                         b = lshift(b, 1);
3254                                         j1 = cmp(b, S);
3255                                         if ((j1 > 0 || j1 == 0 && dig & 1)
3256                                         && dig++ == '9')
3257                                                 goto round_9_up;
3258                                         }
3259  accept_dig:
3260                                 *s++ = dig;
3261                                 goto ret;
3262                                 }
3263                         if (j1 > 0) {
3264 #ifdef Honor_FLT_ROUNDS
3265                                 if (!rounding)
3266                                         goto accept_dig;
3267 #endif
3268                                 if (dig == '9') { /* possible if i == 1 */
3269  round_9_up:
3270                                         *s++ = '9';
3271                                         goto roundoff;
3272                                         }
3273                                 *s++ = dig + 1;
3274                                 goto ret;
3275                                 }
3276 #ifdef Honor_FLT_ROUNDS
3277  keep_dig:
3278 #endif
3279                         *s++ = dig;
3280                         if (i == ilim)
3281                                 break;
3282                         b = multadd(b, 10, 0);
3283                         if (mlo == mhi)
3284                                 mlo = mhi = multadd(mhi, 10, 0);
3285                         else {
3286                                 mlo = multadd(mlo, 10, 0);
3287                                 mhi = multadd(mhi, 10, 0);
3288                                 }
3289                         }
3290                 }
3291         else
3292                 for(i = 1;; i++) {
3293                         *s++ = dig = quorem(b,S) + '0';
3294                         if (!b->x[0] && b->wds <= 1) {
3295 #ifdef SET_INEXACT
3296                                 inexact = 0;
3297 #endif
3298                                 goto ret;
3299                                 }
3300                         if (i >= ilim)
3301                                 break;
3302                         b = multadd(b, 10, 0);
3303                         }
3304
3305         /* Round off last digit */
3306
3307 #ifdef Honor_FLT_ROUNDS
3308         switch(rounding) {
3309           case 0: goto trimzeros;
3310           case 2: goto roundoff;
3311           }
3312 #endif
3313         b = lshift(b, 1);
3314         j = cmp(b, S);
3315         if (j > 0 || j == 0 && dig & 1) {
3316  roundoff:
3317                 while(*--s == '9')
3318                         if (s == s0) {
3319                                 k++;
3320                                 *s++ = '1';
3321                                 goto ret;
3322                                 }
3323                 ++*s++;
3324                 }
3325         else {
3326  trimzeros:
3327                 while(*--s == '0');
3328                 s++;
3329                 }
3330  ret:
3331         Bfree(S);
3332         if (mhi) {
3333                 if (mlo && mlo != mhi)
3334                         Bfree(mlo);
3335                 Bfree(mhi);
3336                 }
3337  ret1:
3338 #ifdef SET_INEXACT
3339         if (inexact) {
3340                 if (!oldinexact) {
3341                         word0(d) = Exp_1 + (70 << Exp_shift);
3342                         word1(d) = 0;
3343                         dval(d) += 1.;
3344                         }
3345                 }
3346         else if (!oldinexact)
3347                 clear_inexact();
3348 #endif
3349         Bfree(b);
3350         *s = 0;
3351         *decpt = k + 1;
3352         if (rve)
3353                 *rve = s;
3354         return s0;
3355         }
3356 #endif
3357
3358 #ifdef __cplusplus
3359 }
3360 #endif