Fix strtod rounding (bug 3479).
[platform/upstream/glibc.git] / stdlib / strtod_l.c
1 /* Convert string representing a number to float value, using given locale.
2    Copyright (C) 1997-2012 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Lesser General Public
8    License as published by the Free Software Foundation; either
9    version 2.1 of the License, or (at your option) any later version.
10
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Lesser General Public License for more details.
15
16    You should have received a copy of the GNU Lesser General Public
17    License along with the GNU C Library; if not, see
18    <http://www.gnu.org/licenses/>.  */
19
20 #include <xlocale.h>
21
22 extern double ____strtod_l_internal (const char *, char **, int, __locale_t);
23 extern unsigned long long int ____strtoull_l_internal (const char *, char **,
24                                                        int, int, __locale_t);
25
26 /* Configuration part.  These macros are defined by `strtold.c',
27    `strtof.c', `wcstod.c', `wcstold.c', and `wcstof.c' to produce the
28    `long double' and `float' versions of the reader.  */
29 #ifndef FLOAT
30 # include <math_ldbl_opt.h>
31 # define FLOAT          double
32 # define FLT            DBL
33 # ifdef USE_WIDE_CHAR
34 #  define STRTOF        wcstod_l
35 #  define __STRTOF      __wcstod_l
36 # else
37 #  define STRTOF        strtod_l
38 #  define __STRTOF      __strtod_l
39 # endif
40 # define MPN2FLOAT      __mpn_construct_double
41 # define FLOAT_HUGE_VAL HUGE_VAL
42 # define SET_MANTISSA(flt, mant) \
43   do { union ieee754_double u;                                                \
44        u.d = (flt);                                                           \
45        if ((mant & 0xfffffffffffffULL) == 0)                                  \
46          mant = 0x8000000000000ULL;                                           \
47        u.ieee.mantissa0 = ((mant) >> 32) & 0xfffff;                           \
48        u.ieee.mantissa1 = (mant) & 0xffffffff;                                \
49        (flt) = u.d;                                                           \
50   } while (0)
51 #endif
52 /* End of configuration part.  */
53 \f
54 #include <ctype.h>
55 #include <errno.h>
56 #include <float.h>
57 #include <ieee754.h>
58 #include "../locale/localeinfo.h"
59 #include <locale.h>
60 #include <math.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <stdint.h>
64
65 /* The gmp headers need some configuration frobs.  */
66 #define HAVE_ALLOCA 1
67
68 /* Include gmp-mparam.h first, such that definitions of _SHORT_LIMB
69    and _LONG_LONG_LIMB in it can take effect into gmp.h.  */
70 #include <gmp-mparam.h>
71 #include <gmp.h>
72 #include "gmp-impl.h"
73 #include "longlong.h"
74 #include "fpioconst.h"
75
76 #include <assert.h>
77
78
79 /* We use this code for the extended locale handling where the
80    function gets as an additional argument the locale which has to be
81    used.  To access the values we have to redefine the _NL_CURRENT and
82    _NL_CURRENT_WORD macros.  */
83 #undef _NL_CURRENT
84 #define _NL_CURRENT(category, item) \
85   (current->values[_NL_ITEM_INDEX (item)].string)
86 #undef _NL_CURRENT_WORD
87 #define _NL_CURRENT_WORD(category, item) \
88   ((uint32_t) current->values[_NL_ITEM_INDEX (item)].word)
89
90 #if defined _LIBC || defined HAVE_WCHAR_H
91 # include <wchar.h>
92 #endif
93
94 #ifdef USE_WIDE_CHAR
95 # include <wctype.h>
96 # define STRING_TYPE wchar_t
97 # define CHAR_TYPE wint_t
98 # define L_(Ch) L##Ch
99 # define ISSPACE(Ch) __iswspace_l ((Ch), loc)
100 # define ISDIGIT(Ch) __iswdigit_l ((Ch), loc)
101 # define ISXDIGIT(Ch) __iswxdigit_l ((Ch), loc)
102 # define TOLOWER(Ch) __towlower_l ((Ch), loc)
103 # define TOLOWER_C(Ch) __towlower_l ((Ch), _nl_C_locobj_ptr)
104 # define STRNCASECMP(S1, S2, N) \
105   __wcsncasecmp_l ((S1), (S2), (N), _nl_C_locobj_ptr)
106 # define STRTOULL(S, E, B) ____wcstoull_l_internal ((S), (E), (B), 0, loc)
107 #else
108 # define STRING_TYPE char
109 # define CHAR_TYPE char
110 # define L_(Ch) Ch
111 # define ISSPACE(Ch) __isspace_l ((Ch), loc)
112 # define ISDIGIT(Ch) __isdigit_l ((Ch), loc)
113 # define ISXDIGIT(Ch) __isxdigit_l ((Ch), loc)
114 # define TOLOWER(Ch) __tolower_l ((Ch), loc)
115 # define TOLOWER_C(Ch) __tolower_l ((Ch), _nl_C_locobj_ptr)
116 # define STRNCASECMP(S1, S2, N) \
117   __strncasecmp_l ((S1), (S2), (N), _nl_C_locobj_ptr)
118 # define STRTOULL(S, E, B) ____strtoull_l_internal ((S), (E), (B), 0, loc)
119 #endif
120
121
122 /* Constants we need from float.h; select the set for the FLOAT precision.  */
123 #define MANT_DIG        PASTE(FLT,_MANT_DIG)
124 #define DIG             PASTE(FLT,_DIG)
125 #define MAX_EXP         PASTE(FLT,_MAX_EXP)
126 #define MIN_EXP         PASTE(FLT,_MIN_EXP)
127 #define MAX_10_EXP      PASTE(FLT,_MAX_10_EXP)
128 #define MIN_10_EXP      PASTE(FLT,_MIN_10_EXP)
129
130 /* Extra macros required to get FLT expanded before the pasting.  */
131 #define PASTE(a,b)      PASTE1(a,b)
132 #define PASTE1(a,b)     a##b
133
134 /* Function to construct a floating point number from an MP integer
135    containing the fraction bits, a base 2 exponent, and a sign flag.  */
136 extern FLOAT MPN2FLOAT (mp_srcptr mpn, int exponent, int negative);
137 \f
138 /* Definitions according to limb size used.  */
139 #if     BITS_PER_MP_LIMB == 32
140 # define MAX_DIG_PER_LIMB       9
141 # define MAX_FAC_PER_LIMB       1000000000UL
142 #elif   BITS_PER_MP_LIMB == 64
143 # define MAX_DIG_PER_LIMB       19
144 # define MAX_FAC_PER_LIMB       10000000000000000000ULL
145 #else
146 # error "mp_limb_t size " BITS_PER_MP_LIMB "not accounted for"
147 #endif
148
149 extern const mp_limb_t _tens_in_limb[MAX_DIG_PER_LIMB + 1];
150 \f
151 #ifndef howmany
152 #define howmany(x,y)            (((x)+((y)-1))/(y))
153 #endif
154 #define SWAP(x, y)              ({ typeof(x) _tmp = x; x = y; y = _tmp; })
155
156 #define RETURN_LIMB_SIZE                howmany (MANT_DIG, BITS_PER_MP_LIMB)
157
158 #define RETURN(val,end)                                                       \
159     do { if (endptr != NULL) *endptr = (STRING_TYPE *) (end);                 \
160          return val; } while (0)
161
162 /* Maximum size necessary for mpn integers to hold floating point
163    numbers.  The largest number we need to hold is 10^n where 2^-n is
164    1/4 ulp of the smallest representable value (that is, n = MANT_DIG
165    - MIN_EXP + 2).  Approximate using 10^3 < 2^10.  */
166 #define MPNSIZE         (howmany (1 + ((MANT_DIG - MIN_EXP + 2) * 10) / 3, \
167                                   BITS_PER_MP_LIMB) + 2)
168 /* Declare an mpn integer variable that big.  */
169 #define MPN_VAR(name)   mp_limb_t name[MPNSIZE]; mp_size_t name##size
170 /* Copy an mpn integer value.  */
171 #define MPN_ASSIGN(dst, src) \
172         memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb_t))
173
174
175 /* Return a floating point number of the needed type according to the given
176    multi-precision number after possible rounding.  */
177 static FLOAT
178 round_and_return (mp_limb_t *retval, intmax_t exponent, int negative,
179                   mp_limb_t round_limb, mp_size_t round_bit, int more_bits)
180 {
181   if (exponent < MIN_EXP - 1)
182     {
183       if (exponent < MIN_EXP - 1 - MANT_DIG)
184         {
185           __set_errno (ERANGE);
186           return 0.0;
187         }
188
189       mp_size_t shift = MIN_EXP - 1 - exponent;
190
191       more_bits |= (round_limb & ((((mp_limb_t) 1) << round_bit) - 1)) != 0;
192       if (shift == MANT_DIG)
193         /* This is a special case to handle the very seldom case where
194            the mantissa will be empty after the shift.  */
195         {
196           int i;
197
198           round_limb = retval[RETURN_LIMB_SIZE - 1];
199           round_bit = (MANT_DIG - 1) % BITS_PER_MP_LIMB;
200           for (i = 0; i < RETURN_LIMB_SIZE; ++i)
201             more_bits |= retval[i] != 0;
202           MPN_ZERO (retval, RETURN_LIMB_SIZE);
203         }
204       else if (shift >= BITS_PER_MP_LIMB)
205         {
206           int i;
207
208           round_limb = retval[(shift - 1) / BITS_PER_MP_LIMB];
209           round_bit = (shift - 1) % BITS_PER_MP_LIMB;
210           for (i = 0; i < (shift - 1) / BITS_PER_MP_LIMB; ++i)
211             more_bits |= retval[i] != 0;
212           more_bits |= ((round_limb & ((((mp_limb_t) 1) << round_bit) - 1))
213                         != 0);
214
215           (void) __mpn_rshift (retval, &retval[shift / BITS_PER_MP_LIMB],
216                                RETURN_LIMB_SIZE - (shift / BITS_PER_MP_LIMB),
217                                shift % BITS_PER_MP_LIMB);
218           MPN_ZERO (&retval[RETURN_LIMB_SIZE - (shift / BITS_PER_MP_LIMB)],
219                     shift / BITS_PER_MP_LIMB);
220         }
221       else if (shift > 0)
222         {
223           round_limb = retval[0];
224           round_bit = shift - 1;
225           (void) __mpn_rshift (retval, retval, RETURN_LIMB_SIZE, shift);
226         }
227       /* This is a hook for the m68k long double format, where the
228          exponent bias is the same for normalized and denormalized
229          numbers.  */
230 #ifndef DENORM_EXP
231 # define DENORM_EXP (MIN_EXP - 2)
232 #endif
233       exponent = DENORM_EXP;
234       __set_errno (ERANGE);
235     }
236
237   if (exponent > MAX_EXP)
238     goto overflow;
239
240   if ((round_limb & (((mp_limb_t) 1) << round_bit)) != 0
241       && (more_bits || (retval[0] & 1) != 0
242           || (round_limb & ((((mp_limb_t) 1) << round_bit) - 1)) != 0))
243     {
244       mp_limb_t cy = __mpn_add_1 (retval, retval, RETURN_LIMB_SIZE, 1);
245
246       if (((MANT_DIG % BITS_PER_MP_LIMB) == 0 && cy) ||
247           ((MANT_DIG % BITS_PER_MP_LIMB) != 0 &&
248            (retval[RETURN_LIMB_SIZE - 1]
249             & (((mp_limb_t) 1) << (MANT_DIG % BITS_PER_MP_LIMB))) != 0))
250         {
251           ++exponent;
252           (void) __mpn_rshift (retval, retval, RETURN_LIMB_SIZE, 1);
253           retval[RETURN_LIMB_SIZE - 1]
254             |= ((mp_limb_t) 1) << ((MANT_DIG - 1) % BITS_PER_MP_LIMB);
255         }
256       else if (exponent == DENORM_EXP
257                && (retval[RETURN_LIMB_SIZE - 1]
258                    & (((mp_limb_t) 1) << ((MANT_DIG - 1) % BITS_PER_MP_LIMB)))
259                != 0)
260           /* The number was denormalized but now normalized.  */
261         exponent = MIN_EXP - 1;
262     }
263
264   if (exponent > MAX_EXP)
265   overflow:
266     return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
267
268   return MPN2FLOAT (retval, exponent, negative);
269 }
270
271
272 /* Read a multi-precision integer starting at STR with exactly DIGCNT digits
273    into N.  Return the size of the number limbs in NSIZE at the first
274    character od the string that is not part of the integer as the function
275    value.  If the EXPONENT is small enough to be taken as an additional
276    factor for the resulting number (see code) multiply by it.  */
277 static const STRING_TYPE *
278 str_to_mpn (const STRING_TYPE *str, int digcnt, mp_limb_t *n, mp_size_t *nsize,
279             intmax_t *exponent
280 #ifndef USE_WIDE_CHAR
281             , const char *decimal, size_t decimal_len, const char *thousands
282 #endif
283
284             )
285 {
286   /* Number of digits for actual limb.  */
287   int cnt = 0;
288   mp_limb_t low = 0;
289   mp_limb_t start;
290
291   *nsize = 0;
292   assert (digcnt > 0);
293   do
294     {
295       if (cnt == MAX_DIG_PER_LIMB)
296         {
297           if (*nsize == 0)
298             {
299               n[0] = low;
300               *nsize = 1;
301             }
302           else
303             {
304               mp_limb_t cy;
305               cy = __mpn_mul_1 (n, n, *nsize, MAX_FAC_PER_LIMB);
306               cy += __mpn_add_1 (n, n, *nsize, low);
307               if (cy != 0)
308                 {
309                   assert (*nsize < MPNSIZE);
310                   n[*nsize] = cy;
311                   ++(*nsize);
312                 }
313             }
314           cnt = 0;
315           low = 0;
316         }
317
318       /* There might be thousands separators or radix characters in
319          the string.  But these all can be ignored because we know the
320          format of the number is correct and we have an exact number
321          of characters to read.  */
322 #ifdef USE_WIDE_CHAR
323       if (*str < L'0' || *str > L'9')
324         ++str;
325 #else
326       if (*str < '0' || *str > '9')
327         {
328           int inner = 0;
329           if (thousands != NULL && *str == *thousands
330               && ({ for (inner = 1; thousands[inner] != '\0'; ++inner)
331                       if (thousands[inner] != str[inner])
332                         break;
333                     thousands[inner] == '\0'; }))
334             str += inner;
335           else
336             str += decimal_len;
337         }
338 #endif
339       low = low * 10 + *str++ - L_('0');
340       ++cnt;
341     }
342   while (--digcnt > 0);
343
344   if (*exponent > 0 && *exponent <= MAX_DIG_PER_LIMB - cnt)
345     {
346       low *= _tens_in_limb[*exponent];
347       start = _tens_in_limb[cnt + *exponent];
348       *exponent = 0;
349     }
350   else
351     start = _tens_in_limb[cnt];
352
353   if (*nsize == 0)
354     {
355       n[0] = low;
356       *nsize = 1;
357     }
358   else
359     {
360       mp_limb_t cy;
361       cy = __mpn_mul_1 (n, n, *nsize, start);
362       cy += __mpn_add_1 (n, n, *nsize, low);
363       if (cy != 0)
364         {
365           assert (*nsize < MPNSIZE);
366           n[(*nsize)++] = cy;
367         }
368     }
369
370   return str;
371 }
372
373
374 /* Shift {PTR, SIZE} COUNT bits to the left, and fill the vacated bits
375    with the COUNT most significant bits of LIMB.
376
377    Tege doesn't like this function so I have to write it here myself. :)
378    --drepper */
379 static inline void
380 __attribute ((always_inline))
381 __mpn_lshift_1 (mp_limb_t *ptr, mp_size_t size, unsigned int count,
382                 mp_limb_t limb)
383 {
384   if (__builtin_constant_p (count) && count == BITS_PER_MP_LIMB)
385     {
386       /* Optimize the case of shifting by exactly a word:
387          just copy words, with no actual bit-shifting.  */
388       mp_size_t i;
389       for (i = size - 1; i > 0; --i)
390         ptr[i] = ptr[i - 1];
391       ptr[0] = limb;
392     }
393   else
394     {
395       (void) __mpn_lshift (ptr, ptr, size, count);
396       ptr[0] |= limb >> (BITS_PER_MP_LIMB - count);
397     }
398 }
399
400
401 #define INTERNAL(x) INTERNAL1(x)
402 #define INTERNAL1(x) __##x##_internal
403 #ifndef ____STRTOF_INTERNAL
404 # define ____STRTOF_INTERNAL INTERNAL (__STRTOF)
405 #endif
406
407 /* This file defines a function to check for correct grouping.  */
408 #include "grouping.h"
409
410
411 /* Return a floating point number with the value of the given string NPTR.
412    Set *ENDPTR to the character after the last used one.  If the number is
413    smaller than the smallest representable number, set `errno' to ERANGE and
414    return 0.0.  If the number is too big to be represented, set `errno' to
415    ERANGE and return HUGE_VAL with the appropriate sign.  */
416 FLOAT
417 ____STRTOF_INTERNAL (nptr, endptr, group, loc)
418      const STRING_TYPE *nptr;
419      STRING_TYPE **endptr;
420      int group;
421      __locale_t loc;
422 {
423   int negative;                 /* The sign of the number.  */
424   MPN_VAR (num);                /* MP representation of the number.  */
425   intmax_t exponent;            /* Exponent of the number.  */
426
427   /* Numbers starting `0X' or `0x' have to be processed with base 16.  */
428   int base = 10;
429
430   /* When we have to compute fractional digits we form a fraction with a
431      second multi-precision number (and we sometimes need a second for
432      temporary results).  */
433   MPN_VAR (den);
434
435   /* Representation for the return value.  */
436   mp_limb_t retval[RETURN_LIMB_SIZE];
437   /* Number of bits currently in result value.  */
438   int bits;
439
440   /* Running pointer after the last character processed in the string.  */
441   const STRING_TYPE *cp, *tp;
442   /* Start of significant part of the number.  */
443   const STRING_TYPE *startp, *start_of_digits;
444   /* Points at the character following the integer and fractional digits.  */
445   const STRING_TYPE *expp;
446   /* Total number of digit and number of digits in integer part.  */
447   size_t dig_no, int_no, lead_zero;
448   /* Contains the last character read.  */
449   CHAR_TYPE c;
450
451 /* We should get wint_t from <stddef.h>, but not all GCC versions define it
452    there.  So define it ourselves if it remains undefined.  */
453 #ifndef _WINT_T
454   typedef unsigned int wint_t;
455 #endif
456   /* The radix character of the current locale.  */
457 #ifdef USE_WIDE_CHAR
458   wchar_t decimal;
459 #else
460   const char *decimal;
461   size_t decimal_len;
462 #endif
463   /* The thousands character of the current locale.  */
464 #ifdef USE_WIDE_CHAR
465   wchar_t thousands = L'\0';
466 #else
467   const char *thousands = NULL;
468 #endif
469   /* The numeric grouping specification of the current locale,
470      in the format described in <locale.h>.  */
471   const char *grouping;
472   /* Used in several places.  */
473   int cnt;
474
475   struct __locale_data *current = loc->__locales[LC_NUMERIC];
476
477   if (__builtin_expect (group, 0))
478     {
479       grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
480       if (*grouping <= 0 || *grouping == CHAR_MAX)
481         grouping = NULL;
482       else
483         {
484           /* Figure out the thousands separator character.  */
485 #ifdef USE_WIDE_CHAR
486           thousands = _NL_CURRENT_WORD (LC_NUMERIC,
487                                         _NL_NUMERIC_THOUSANDS_SEP_WC);
488           if (thousands == L'\0')
489             grouping = NULL;
490 #else
491           thousands = _NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP);
492           if (*thousands == '\0')
493             {
494               thousands = NULL;
495               grouping = NULL;
496             }
497 #endif
498         }
499     }
500   else
501     grouping = NULL;
502
503   /* Find the locale's decimal point character.  */
504 #ifdef USE_WIDE_CHAR
505   decimal = _NL_CURRENT_WORD (LC_NUMERIC, _NL_NUMERIC_DECIMAL_POINT_WC);
506   assert (decimal != L'\0');
507 # define decimal_len 1
508 #else
509   decimal = _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
510   decimal_len = strlen (decimal);
511   assert (decimal_len > 0);
512 #endif
513
514   /* Prepare number representation.  */
515   exponent = 0;
516   negative = 0;
517   bits = 0;
518
519   /* Parse string to get maximal legal prefix.  We need the number of
520      characters of the integer part, the fractional part and the exponent.  */
521   cp = nptr - 1;
522   /* Ignore leading white space.  */
523   do
524     c = *++cp;
525   while (ISSPACE (c));
526
527   /* Get sign of the result.  */
528   if (c == L_('-'))
529     {
530       negative = 1;
531       c = *++cp;
532     }
533   else if (c == L_('+'))
534     c = *++cp;
535
536   /* Return 0.0 if no legal string is found.
537      No character is used even if a sign was found.  */
538 #ifdef USE_WIDE_CHAR
539   if (c == (wint_t) decimal
540       && (wint_t) cp[1] >= L'0' && (wint_t) cp[1] <= L'9')
541     {
542       /* We accept it.  This funny construct is here only to indent
543          the code correctly.  */
544     }
545 #else
546   for (cnt = 0; decimal[cnt] != '\0'; ++cnt)
547     if (cp[cnt] != decimal[cnt])
548       break;
549   if (decimal[cnt] == '\0' && cp[cnt] >= '0' && cp[cnt] <= '9')
550     {
551       /* We accept it.  This funny construct is here only to indent
552          the code correctly.  */
553     }
554 #endif
555   else if (c < L_('0') || c > L_('9'))
556     {
557       /* Check for `INF' or `INFINITY'.  */
558       CHAR_TYPE lowc = TOLOWER_C (c);
559
560       if (lowc == L_('i') && STRNCASECMP (cp, L_("inf"), 3) == 0)
561         {
562           /* Return +/- infinity.  */
563           if (endptr != NULL)
564             *endptr = (STRING_TYPE *)
565                       (cp + (STRNCASECMP (cp + 3, L_("inity"), 5) == 0
566                              ? 8 : 3));
567
568           return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
569         }
570
571       if (lowc == L_('n') && STRNCASECMP (cp, L_("nan"), 3) == 0)
572         {
573           /* Return NaN.  */
574           FLOAT retval = NAN;
575
576           cp += 3;
577
578           /* Match `(n-char-sequence-digit)'.  */
579           if (*cp == L_('('))
580             {
581               const STRING_TYPE *startp = cp;
582               do
583                 ++cp;
584               while ((*cp >= L_('0') && *cp <= L_('9'))
585                      || ({ CHAR_TYPE lo = TOLOWER (*cp);
586                            lo >= L_('a') && lo <= L_('z'); })
587                      || *cp == L_('_'));
588
589               if (*cp != L_(')'))
590                 /* The closing brace is missing.  Only match the NAN
591                    part.  */
592                 cp = startp;
593               else
594                 {
595                   /* This is a system-dependent way to specify the
596                      bitmask used for the NaN.  We expect it to be
597                      a number which is put in the mantissa of the
598                      number.  */
599                   STRING_TYPE *endp;
600                   unsigned long long int mant;
601
602                   mant = STRTOULL (startp + 1, &endp, 0);
603                   if (endp == cp)
604                     SET_MANTISSA (retval, mant);
605
606                   /* Consume the closing brace.  */
607                   ++cp;
608                 }
609             }
610
611           if (endptr != NULL)
612             *endptr = (STRING_TYPE *) cp;
613
614           return retval;
615         }
616
617       /* It is really a text we do not recognize.  */
618       RETURN (0.0, nptr);
619     }
620
621   /* First look whether we are faced with a hexadecimal number.  */
622   if (c == L_('0') && TOLOWER (cp[1]) == L_('x'))
623     {
624       /* Okay, it is a hexa-decimal number.  Remember this and skip
625          the characters.  BTW: hexadecimal numbers must not be
626          grouped.  */
627       base = 16;
628       cp += 2;
629       c = *cp;
630       grouping = NULL;
631     }
632
633   /* Record the start of the digits, in case we will check their grouping.  */
634   start_of_digits = startp = cp;
635
636   /* Ignore leading zeroes.  This helps us to avoid useless computations.  */
637 #ifdef USE_WIDE_CHAR
638   while (c == L'0' || ((wint_t) thousands != L'\0' && c == (wint_t) thousands))
639     c = *++cp;
640 #else
641   if (__builtin_expect (thousands == NULL, 1))
642     while (c == '0')
643       c = *++cp;
644   else
645     {
646       /* We also have the multibyte thousands string.  */
647       while (1)
648         {
649           if (c != '0')
650             {
651               for (cnt = 0; thousands[cnt] != '\0'; ++cnt)
652                 if (thousands[cnt] != cp[cnt])
653                   break;
654               if (thousands[cnt] != '\0')
655                 break;
656               cp += cnt - 1;
657             }
658           c = *++cp;
659         }
660     }
661 #endif
662
663   /* If no other digit but a '0' is found the result is 0.0.
664      Return current read pointer.  */
665   CHAR_TYPE lowc = TOLOWER (c);
666   if (!((c >= L_('0') && c <= L_('9'))
667         || (base == 16 && lowc >= L_('a') && lowc <= L_('f'))
668         || (
669 #ifdef USE_WIDE_CHAR
670             c == (wint_t) decimal
671 #else
672             ({ for (cnt = 0; decimal[cnt] != '\0'; ++cnt)
673                  if (decimal[cnt] != cp[cnt])
674                    break;
675                decimal[cnt] == '\0'; })
676 #endif
677             /* '0x.' alone is not a valid hexadecimal number.
678                '.' alone is not valid either, but that has been checked
679                already earlier.  */
680             && (base != 16
681                 || cp != start_of_digits
682                 || (cp[decimal_len] >= L_('0') && cp[decimal_len] <= L_('9'))
683                 || ({ CHAR_TYPE lo = TOLOWER (cp[decimal_len]);
684                       lo >= L_('a') && lo <= L_('f'); })))
685         || (base == 16 && (cp != start_of_digits
686                            && lowc == L_('p')))
687         || (base != 16 && lowc == L_('e'))))
688     {
689 #ifdef USE_WIDE_CHAR
690       tp = __correctly_grouped_prefixwc (start_of_digits, cp, thousands,
691                                          grouping);
692 #else
693       tp = __correctly_grouped_prefixmb (start_of_digits, cp, thousands,
694                                          grouping);
695 #endif
696       /* If TP is at the start of the digits, there was no correctly
697          grouped prefix of the string; so no number found.  */
698       RETURN (negative ? -0.0 : 0.0,
699               tp == start_of_digits ? (base == 16 ? cp - 1 : nptr) : tp);
700     }
701
702   /* Remember first significant digit and read following characters until the
703      decimal point, exponent character or any non-FP number character.  */
704   startp = cp;
705   dig_no = 0;
706   while (1)
707     {
708       if ((c >= L_('0') && c <= L_('9'))
709           || (base == 16
710               && ({ CHAR_TYPE lo = TOLOWER (c);
711                     lo >= L_('a') && lo <= L_('f'); })))
712         ++dig_no;
713       else
714         {
715 #ifdef USE_WIDE_CHAR
716           if (__builtin_expect ((wint_t) thousands == L'\0', 1)
717               || c != (wint_t) thousands)
718             /* Not a digit or separator: end of the integer part.  */
719             break;
720 #else
721           if (__builtin_expect (thousands == NULL, 1))
722             break;
723           else
724             {
725               for (cnt = 0; thousands[cnt] != '\0'; ++cnt)
726                 if (thousands[cnt] != cp[cnt])
727                   break;
728               if (thousands[cnt] != '\0')
729                 break;
730               cp += cnt - 1;
731             }
732 #endif
733         }
734       c = *++cp;
735     }
736
737   if (__builtin_expect (grouping != NULL, 0) && cp > start_of_digits)
738     {
739       /* Check the grouping of the digits.  */
740 #ifdef USE_WIDE_CHAR
741       tp = __correctly_grouped_prefixwc (start_of_digits, cp, thousands,
742                                          grouping);
743 #else
744       tp = __correctly_grouped_prefixmb (start_of_digits, cp, thousands,
745                                          grouping);
746 #endif
747       if (cp != tp)
748         {
749           /* Less than the entire string was correctly grouped.  */
750
751           if (tp == start_of_digits)
752             /* No valid group of numbers at all: no valid number.  */
753             RETURN (0.0, nptr);
754
755           if (tp < startp)
756             /* The number is validly grouped, but consists
757                only of zeroes.  The whole value is zero.  */
758             RETURN (negative ? -0.0 : 0.0, tp);
759
760           /* Recompute DIG_NO so we won't read more digits than
761              are properly grouped.  */
762           cp = tp;
763           dig_no = 0;
764           for (tp = startp; tp < cp; ++tp)
765             if (*tp >= L_('0') && *tp <= L_('9'))
766               ++dig_no;
767
768           int_no = dig_no;
769           lead_zero = 0;
770
771           goto number_parsed;
772         }
773     }
774
775   /* We have the number of digits in the integer part.  Whether these
776      are all or any is really a fractional digit will be decided
777      later.  */
778   int_no = dig_no;
779   lead_zero = int_no == 0 ? (size_t) -1 : 0;
780
781   /* Read the fractional digits.  A special case are the 'american
782      style' numbers like `16.' i.e. with decimal point but without
783      trailing digits.  */
784   if (
785 #ifdef USE_WIDE_CHAR
786       c == (wint_t) decimal
787 #else
788       ({ for (cnt = 0; decimal[cnt] != '\0'; ++cnt)
789            if (decimal[cnt] != cp[cnt])
790              break;
791          decimal[cnt] == '\0'; })
792 #endif
793       )
794     {
795       cp += decimal_len;
796       c = *cp;
797       while ((c >= L_('0') && c <= L_('9')) ||
798              (base == 16 && ({ CHAR_TYPE lo = TOLOWER (c);
799                                lo >= L_('a') && lo <= L_('f'); })))
800         {
801           if (c != L_('0') && lead_zero == (size_t) -1)
802             lead_zero = dig_no - int_no;
803           ++dig_no;
804           c = *++cp;
805         }
806     }
807   assert (dig_no <= (uintmax_t) INTMAX_MAX);
808
809   /* Remember start of exponent (if any).  */
810   expp = cp;
811
812   /* Read exponent.  */
813   lowc = TOLOWER (c);
814   if ((base == 16 && lowc == L_('p'))
815       || (base != 16 && lowc == L_('e')))
816     {
817       int exp_negative = 0;
818
819       c = *++cp;
820       if (c == L_('-'))
821         {
822           exp_negative = 1;
823           c = *++cp;
824         }
825       else if (c == L_('+'))
826         c = *++cp;
827
828       if (c >= L_('0') && c <= L_('9'))
829         {
830           intmax_t exp_limit;
831
832           /* Get the exponent limit. */
833           if (base == 16)
834             {
835               if (exp_negative)
836                 {
837                   assert (int_no <= (uintmax_t) (INTMAX_MAX
838                                                  + MIN_EXP - MANT_DIG) / 4);
839                   exp_limit = -MIN_EXP + MANT_DIG + 4 * (intmax_t) int_no;
840                 }
841               else
842                 {
843                   if (int_no)
844                     {
845                       assert (lead_zero == 0
846                               && int_no <= (uintmax_t) INTMAX_MAX / 4);
847                       exp_limit = MAX_EXP - 4 * (intmax_t) int_no + 3;
848                     }
849                   else if (lead_zero == (size_t) -1)
850                     {
851                       /* The number is zero and this limit is
852                          arbitrary.  */
853                       exp_limit = MAX_EXP + 3;
854                     }
855                   else
856                     {
857                       assert (lead_zero
858                               <= (uintmax_t) (INTMAX_MAX - MAX_EXP - 3) / 4);
859                       exp_limit = (MAX_EXP
860                                    + 4 * (intmax_t) lead_zero
861                                    + 3);
862                     }
863                 }
864             }
865           else
866             {
867               if (exp_negative)
868                 {
869                   assert (int_no
870                           <= (uintmax_t) (INTMAX_MAX + MIN_10_EXP - MANT_DIG));
871                   exp_limit = -MIN_10_EXP + MANT_DIG + (intmax_t) int_no;
872                 }
873               else
874                 {
875                   if (int_no)
876                     {
877                       assert (lead_zero == 0
878                               && int_no <= (uintmax_t) INTMAX_MAX);
879                       exp_limit = MAX_10_EXP - (intmax_t) int_no + 1;
880                     }
881                   else if (lead_zero == (size_t) -1)
882                     {
883                       /* The number is zero and this limit is
884                          arbitrary.  */
885                       exp_limit = MAX_10_EXP + 1;
886                     }
887                   else
888                     {
889                       assert (lead_zero
890                               <= (uintmax_t) (INTMAX_MAX - MAX_10_EXP - 1));
891                       exp_limit = MAX_10_EXP + (intmax_t) lead_zero + 1;
892                     }
893                 }
894             }
895
896           if (exp_limit < 0)
897             exp_limit = 0;
898
899           do
900             {
901               if (__builtin_expect ((exponent > exp_limit / 10
902                                      || (exponent == exp_limit / 10
903                                          && c - L_('0') > exp_limit % 10)), 0))
904                 /* The exponent is too large/small to represent a valid
905                    number.  */
906                 {
907                   FLOAT result;
908
909                   /* We have to take care for special situation: a joker
910                      might have written "0.0e100000" which is in fact
911                      zero.  */
912                   if (lead_zero == (size_t) -1)
913                     result = negative ? -0.0 : 0.0;
914                   else
915                     {
916                       /* Overflow or underflow.  */
917                       __set_errno (ERANGE);
918                       result = (exp_negative ? (negative ? -0.0 : 0.0) :
919                                 negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL);
920                     }
921
922                   /* Accept all following digits as part of the exponent.  */
923                   do
924                     ++cp;
925                   while (*cp >= L_('0') && *cp <= L_('9'));
926
927                   RETURN (result, cp);
928                   /* NOTREACHED */
929                 }
930
931               exponent *= 10;
932               exponent += c - L_('0');
933
934               c = *++cp;
935             }
936           while (c >= L_('0') && c <= L_('9'));
937
938           if (exp_negative)
939             exponent = -exponent;
940         }
941       else
942         cp = expp;
943     }
944
945   /* We don't want to have to work with trailing zeroes after the radix.  */
946   if (dig_no > int_no)
947     {
948       while (expp[-1] == L_('0'))
949         {
950           --expp;
951           --dig_no;
952         }
953       assert (dig_no >= int_no);
954     }
955
956   if (dig_no == int_no && dig_no > 0 && exponent < 0)
957     do
958       {
959         while (! (base == 16 ? ISXDIGIT (expp[-1]) : ISDIGIT (expp[-1])))
960           --expp;
961
962         if (expp[-1] != L_('0'))
963           break;
964
965         --expp;
966         --dig_no;
967         --int_no;
968         exponent += base == 16 ? 4 : 1;
969       }
970     while (dig_no > 0 && exponent < 0);
971
972  number_parsed:
973
974   /* The whole string is parsed.  Store the address of the next character.  */
975   if (endptr)
976     *endptr = (STRING_TYPE *) cp;
977
978   if (dig_no == 0)
979     return negative ? -0.0 : 0.0;
980
981   if (lead_zero)
982     {
983       /* Find the decimal point */
984 #ifdef USE_WIDE_CHAR
985       while (*startp != decimal)
986         ++startp;
987 #else
988       while (1)
989         {
990           if (*startp == decimal[0])
991             {
992               for (cnt = 1; decimal[cnt] != '\0'; ++cnt)
993                 if (decimal[cnt] != startp[cnt])
994                   break;
995               if (decimal[cnt] == '\0')
996                 break;
997             }
998           ++startp;
999         }
1000 #endif
1001       startp += lead_zero + decimal_len;
1002       assert (lead_zero <= (base == 16
1003                             ? (uintmax_t) INTMAX_MAX / 4
1004                             : (uintmax_t) INTMAX_MAX));
1005       assert (lead_zero <= (base == 16
1006                             ? ((uintmax_t) exponent
1007                                - (uintmax_t) INTMAX_MIN) / 4
1008                             : ((uintmax_t) exponent - (uintmax_t) INTMAX_MIN)));
1009       exponent -= base == 16 ? 4 * (intmax_t) lead_zero : (intmax_t) lead_zero;
1010       dig_no -= lead_zero;
1011     }
1012
1013   /* If the BASE is 16 we can use a simpler algorithm.  */
1014   if (base == 16)
1015     {
1016       static const int nbits[16] = { 0, 1, 2, 2, 3, 3, 3, 3,
1017                                      4, 4, 4, 4, 4, 4, 4, 4 };
1018       int idx = (MANT_DIG - 1) / BITS_PER_MP_LIMB;
1019       int pos = (MANT_DIG - 1) % BITS_PER_MP_LIMB;
1020       mp_limb_t val;
1021
1022       while (!ISXDIGIT (*startp))
1023         ++startp;
1024       while (*startp == L_('0'))
1025         ++startp;
1026       if (ISDIGIT (*startp))
1027         val = *startp++ - L_('0');
1028       else
1029         val = 10 + TOLOWER (*startp++) - L_('a');
1030       bits = nbits[val];
1031       /* We cannot have a leading zero.  */
1032       assert (bits != 0);
1033
1034       if (pos + 1 >= 4 || pos + 1 >= bits)
1035         {
1036           /* We don't have to care for wrapping.  This is the normal
1037              case so we add the first clause in the `if' expression as
1038              an optimization.  It is a compile-time constant and so does
1039              not cost anything.  */
1040           retval[idx] = val << (pos - bits + 1);
1041           pos -= bits;
1042         }
1043       else
1044         {
1045           retval[idx--] = val >> (bits - pos - 1);
1046           retval[idx] = val << (BITS_PER_MP_LIMB - (bits - pos - 1));
1047           pos = BITS_PER_MP_LIMB - 1 - (bits - pos - 1);
1048         }
1049
1050       /* Adjust the exponent for the bits we are shifting in.  */
1051       assert (int_no <= (uintmax_t) (exponent < 0
1052                                      ? (INTMAX_MAX - bits + 1) / 4
1053                                      : (INTMAX_MAX - exponent - bits + 1) / 4));
1054       exponent += bits - 1 + ((intmax_t) int_no - 1) * 4;
1055
1056       while (--dig_no > 0 && idx >= 0)
1057         {
1058           if (!ISXDIGIT (*startp))
1059             startp += decimal_len;
1060           if (ISDIGIT (*startp))
1061             val = *startp++ - L_('0');
1062           else
1063             val = 10 + TOLOWER (*startp++) - L_('a');
1064
1065           if (pos + 1 >= 4)
1066             {
1067               retval[idx] |= val << (pos - 4 + 1);
1068               pos -= 4;
1069             }
1070           else
1071             {
1072               retval[idx--] |= val >> (4 - pos - 1);
1073               val <<= BITS_PER_MP_LIMB - (4 - pos - 1);
1074               if (idx < 0)
1075                 {
1076                   int rest_nonzero = 0;
1077                   while (--dig_no > 0)
1078                     {
1079                       if (*startp != L_('0'))
1080                         {
1081                           rest_nonzero = 1;
1082                           break;
1083                         }
1084                       startp++;
1085                     }
1086                   return round_and_return (retval, exponent, negative, val,
1087                                            BITS_PER_MP_LIMB - 1, rest_nonzero);
1088                 }
1089
1090               retval[idx] = val;
1091               pos = BITS_PER_MP_LIMB - 1 - (4 - pos - 1);
1092             }
1093         }
1094
1095       /* We ran out of digits.  */
1096       MPN_ZERO (retval, idx);
1097
1098       return round_and_return (retval, exponent, negative, 0, 0, 0);
1099     }
1100
1101   /* Now we have the number of digits in total and the integer digits as well
1102      as the exponent and its sign.  We can decide whether the read digits are
1103      really integer digits or belong to the fractional part; i.e. we normalize
1104      123e-2 to 1.23.  */
1105   {
1106     register intmax_t incr = (exponent < 0
1107                               ? MAX (-(intmax_t) int_no, exponent)
1108                               : MIN ((intmax_t) dig_no - (intmax_t) int_no,
1109                                      exponent));
1110     int_no += incr;
1111     exponent -= incr;
1112   }
1113
1114   if (__builtin_expect (exponent > MAX_10_EXP + 1 - (intmax_t) int_no, 0))
1115     {
1116       __set_errno (ERANGE);
1117       return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
1118     }
1119
1120   if (__builtin_expect (exponent < MIN_10_EXP - (DIG + 1), 0))
1121     {
1122       __set_errno (ERANGE);
1123       return negative ? -0.0 : 0.0;
1124     }
1125
1126   if (int_no > 0)
1127     {
1128       /* Read the integer part as a multi-precision number to NUM.  */
1129       startp = str_to_mpn (startp, int_no, num, &numsize, &exponent
1130 #ifndef USE_WIDE_CHAR
1131                            , decimal, decimal_len, thousands
1132 #endif
1133                            );
1134
1135       if (exponent > 0)
1136         {
1137           /* We now multiply the gained number by the given power of ten.  */
1138           mp_limb_t *psrc = num;
1139           mp_limb_t *pdest = den;
1140           int expbit = 1;
1141           const struct mp_power *ttab = &_fpioconst_pow10[0];
1142
1143           do
1144             {
1145               if ((exponent & expbit) != 0)
1146                 {
1147                   size_t size = ttab->arraysize - _FPIO_CONST_OFFSET;
1148                   mp_limb_t cy;
1149                   exponent ^= expbit;
1150
1151                   /* FIXME: not the whole multiplication has to be
1152                      done.  If we have the needed number of bits we
1153                      only need the information whether more non-zero
1154                      bits follow.  */
1155                   if (numsize >= ttab->arraysize - _FPIO_CONST_OFFSET)
1156                     cy = __mpn_mul (pdest, psrc, numsize,
1157                                     &__tens[ttab->arrayoff
1158                                            + _FPIO_CONST_OFFSET],
1159                                     size);
1160                   else
1161                     cy = __mpn_mul (pdest, &__tens[ttab->arrayoff
1162                                                   + _FPIO_CONST_OFFSET],
1163                                     size, psrc, numsize);
1164                   numsize += size;
1165                   if (cy == 0)
1166                     --numsize;
1167                   (void) SWAP (psrc, pdest);
1168                 }
1169               expbit <<= 1;
1170               ++ttab;
1171             }
1172           while (exponent != 0);
1173
1174           if (psrc == den)
1175             memcpy (num, den, numsize * sizeof (mp_limb_t));
1176         }
1177
1178       /* Determine how many bits of the result we already have.  */
1179       count_leading_zeros (bits, num[numsize - 1]);
1180       bits = numsize * BITS_PER_MP_LIMB - bits;
1181
1182       /* Now we know the exponent of the number in base two.
1183          Check it against the maximum possible exponent.  */
1184       if (__builtin_expect (bits > MAX_EXP, 0))
1185         {
1186           __set_errno (ERANGE);
1187           return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
1188         }
1189
1190       /* We have already the first BITS bits of the result.  Together with
1191          the information whether more non-zero bits follow this is enough
1192          to determine the result.  */
1193       if (bits > MANT_DIG)
1194         {
1195           int i;
1196           const mp_size_t least_idx = (bits - MANT_DIG) / BITS_PER_MP_LIMB;
1197           const mp_size_t least_bit = (bits - MANT_DIG) % BITS_PER_MP_LIMB;
1198           const mp_size_t round_idx = least_bit == 0 ? least_idx - 1
1199                                                      : least_idx;
1200           const mp_size_t round_bit = least_bit == 0 ? BITS_PER_MP_LIMB - 1
1201                                                      : least_bit - 1;
1202
1203           if (least_bit == 0)
1204             memcpy (retval, &num[least_idx],
1205                     RETURN_LIMB_SIZE * sizeof (mp_limb_t));
1206           else
1207             {
1208               for (i = least_idx; i < numsize - 1; ++i)
1209                 retval[i - least_idx] = (num[i] >> least_bit)
1210                                         | (num[i + 1]
1211                                            << (BITS_PER_MP_LIMB - least_bit));
1212               if (i - least_idx < RETURN_LIMB_SIZE)
1213                 retval[RETURN_LIMB_SIZE - 1] = num[i] >> least_bit;
1214             }
1215
1216           /* Check whether any limb beside the ones in RETVAL are non-zero.  */
1217           for (i = 0; num[i] == 0; ++i)
1218             ;
1219
1220           return round_and_return (retval, bits - 1, negative,
1221                                    num[round_idx], round_bit,
1222                                    int_no < dig_no || i < round_idx);
1223           /* NOTREACHED */
1224         }
1225       else if (dig_no == int_no)
1226         {
1227           const mp_size_t target_bit = (MANT_DIG - 1) % BITS_PER_MP_LIMB;
1228           const mp_size_t is_bit = (bits - 1) % BITS_PER_MP_LIMB;
1229
1230           if (target_bit == is_bit)
1231             {
1232               memcpy (&retval[RETURN_LIMB_SIZE - numsize], num,
1233                       numsize * sizeof (mp_limb_t));
1234               /* FIXME: the following loop can be avoided if we assume a
1235                  maximal MANT_DIG value.  */
1236               MPN_ZERO (retval, RETURN_LIMB_SIZE - numsize);
1237             }
1238           else if (target_bit > is_bit)
1239             {
1240               (void) __mpn_lshift (&retval[RETURN_LIMB_SIZE - numsize],
1241                                    num, numsize, target_bit - is_bit);
1242               /* FIXME: the following loop can be avoided if we assume a
1243                  maximal MANT_DIG value.  */
1244               MPN_ZERO (retval, RETURN_LIMB_SIZE - numsize);
1245             }
1246           else
1247             {
1248               mp_limb_t cy;
1249               assert (numsize < RETURN_LIMB_SIZE);
1250
1251               cy = __mpn_rshift (&retval[RETURN_LIMB_SIZE - numsize],
1252                                  num, numsize, is_bit - target_bit);
1253               retval[RETURN_LIMB_SIZE - numsize - 1] = cy;
1254               /* FIXME: the following loop can be avoided if we assume a
1255                  maximal MANT_DIG value.  */
1256               MPN_ZERO (retval, RETURN_LIMB_SIZE - numsize - 1);
1257             }
1258
1259           return round_and_return (retval, bits - 1, negative, 0, 0, 0);
1260           /* NOTREACHED */
1261         }
1262
1263       /* Store the bits we already have.  */
1264       memcpy (retval, num, numsize * sizeof (mp_limb_t));
1265 #if RETURN_LIMB_SIZE > 1
1266       if (numsize < RETURN_LIMB_SIZE)
1267 # if RETURN_LIMB_SIZE == 2
1268         retval[numsize] = 0;
1269 # else
1270         MPN_ZERO (retval + numsize, RETURN_LIMB_SIZE - numsize);
1271 # endif
1272 #endif
1273     }
1274
1275   /* We have to compute at least some of the fractional digits.  */
1276   {
1277     /* We construct a fraction and the result of the division gives us
1278        the needed digits.  The denominator is 1.0 multiplied by the
1279        exponent of the lowest digit; i.e. 0.123 gives 123 / 1000 and
1280        123e-6 gives 123 / 1000000.  */
1281
1282     int expbit;
1283     int neg_exp;
1284     int more_bits;
1285     int need_frac_digits;
1286     mp_limb_t cy;
1287     mp_limb_t *psrc = den;
1288     mp_limb_t *pdest = num;
1289     const struct mp_power *ttab = &_fpioconst_pow10[0];
1290
1291     assert (dig_no > int_no
1292             && exponent <= 0
1293             && exponent >= MIN_10_EXP - (DIG + 1));
1294
1295     /* We need to compute MANT_DIG - BITS fractional bits that lie
1296        within the mantissa of the result, the following bit for
1297        rounding, and to know whether any subsequent bit is 0.
1298        Computing a bit with value 2^-n means looking at n digits after
1299        the decimal point.  */
1300     if (bits > 0)
1301       {
1302         /* The bits required are those immediately after the point.  */
1303         assert (int_no > 0 && exponent == 0);
1304         need_frac_digits = 1 + MANT_DIG - bits;
1305       }
1306     else
1307       {
1308         /* The number is in the form .123eEXPONENT.  */
1309         assert (int_no == 0 && *startp != L_('0'));
1310         /* The number is at least 10^(EXPONENT-1), and 10^3 <
1311            2^10.  */
1312         int neg_exp_2 = ((1 - exponent) * 10) / 3 + 1;
1313         /* The number is at least 2^-NEG_EXP_2.  We need up to
1314            MANT_DIG bits following that bit.  */
1315         need_frac_digits = neg_exp_2 + MANT_DIG;
1316         /* However, we never need bits beyond 1/4 ulp of the smallest
1317            representable value.  (That 1/4 ulp bit is only needed to
1318            determine tinyness on machines where tinyness is determined
1319            after rounding.)  */
1320         if (need_frac_digits > MANT_DIG - MIN_EXP + 2)
1321           need_frac_digits = MANT_DIG - MIN_EXP + 2;
1322         /* At this point, NEED_FRAC_DIGITS is the total number of
1323            digits needed after the point, but some of those may be
1324            leading 0s.  */
1325         need_frac_digits += exponent;
1326         /* Any cases underflowing enough that none of the fractional
1327            digits are needed should have been caught earlier (such
1328            cases are on the order of 10^-n or smaller where 2^-n is
1329            the least subnormal).  */
1330         assert (need_frac_digits > 0);
1331       }
1332
1333     if (need_frac_digits > (intmax_t) dig_no - (intmax_t) int_no)
1334       need_frac_digits = (intmax_t) dig_no - (intmax_t) int_no;
1335
1336     if ((intmax_t) dig_no > (intmax_t) int_no + need_frac_digits)
1337       {
1338         dig_no = int_no + need_frac_digits;
1339         more_bits = 1;
1340       }
1341     else
1342       more_bits = 0;
1343
1344     neg_exp = (intmax_t) dig_no - (intmax_t) int_no - exponent;
1345
1346     /* Construct the denominator.  */
1347     densize = 0;
1348     expbit = 1;
1349     do
1350       {
1351         if ((neg_exp & expbit) != 0)
1352           {
1353             mp_limb_t cy;
1354             neg_exp ^= expbit;
1355
1356             if (densize == 0)
1357               {
1358                 densize = ttab->arraysize - _FPIO_CONST_OFFSET;
1359                 memcpy (psrc, &__tens[ttab->arrayoff + _FPIO_CONST_OFFSET],
1360                         densize * sizeof (mp_limb_t));
1361               }
1362             else
1363               {
1364                 cy = __mpn_mul (pdest, &__tens[ttab->arrayoff
1365                                               + _FPIO_CONST_OFFSET],
1366                                 ttab->arraysize - _FPIO_CONST_OFFSET,
1367                                 psrc, densize);
1368                 densize += ttab->arraysize - _FPIO_CONST_OFFSET;
1369                 if (cy == 0)
1370                   --densize;
1371                 (void) SWAP (psrc, pdest);
1372               }
1373           }
1374         expbit <<= 1;
1375         ++ttab;
1376       }
1377     while (neg_exp != 0);
1378
1379     if (psrc == num)
1380       memcpy (den, num, densize * sizeof (mp_limb_t));
1381
1382     /* Read the fractional digits from the string.  */
1383     (void) str_to_mpn (startp, dig_no - int_no, num, &numsize, &exponent
1384 #ifndef USE_WIDE_CHAR
1385                        , decimal, decimal_len, thousands
1386 #endif
1387                        );
1388
1389     /* We now have to shift both numbers so that the highest bit in the
1390        denominator is set.  In the same process we copy the numerator to
1391        a high place in the array so that the division constructs the wanted
1392        digits.  This is done by a "quasi fix point" number representation.
1393
1394        num:   ddddddddddd . 0000000000000000000000
1395               |--- m ---|
1396        den:                            ddddddddddd      n >= m
1397                                        |--- n ---|
1398      */
1399
1400     count_leading_zeros (cnt, den[densize - 1]);
1401
1402     if (cnt > 0)
1403       {
1404         /* Don't call `mpn_shift' with a count of zero since the specification
1405            does not allow this.  */
1406         (void) __mpn_lshift (den, den, densize, cnt);
1407         cy = __mpn_lshift (num, num, numsize, cnt);
1408         if (cy != 0)
1409           num[numsize++] = cy;
1410       }
1411
1412     /* Now we are ready for the division.  But it is not necessary to
1413        do a full multi-precision division because we only need a small
1414        number of bits for the result.  So we do not use __mpn_divmod
1415        here but instead do the division here by hand and stop whenever
1416        the needed number of bits is reached.  The code itself comes
1417        from the GNU MP Library by Torbj\"orn Granlund.  */
1418
1419     exponent = bits;
1420
1421     switch (densize)
1422       {
1423       case 1:
1424         {
1425           mp_limb_t d, n, quot;
1426           int used = 0;
1427
1428           n = num[0];
1429           d = den[0];
1430           assert (numsize == 1 && n < d);
1431
1432           do
1433             {
1434               udiv_qrnnd (quot, n, n, 0, d);
1435
1436 #define got_limb                                                              \
1437               if (bits == 0)                                                  \
1438                 {                                                             \
1439                   register int cnt;                                           \
1440                   if (quot == 0)                                              \
1441                     cnt = BITS_PER_MP_LIMB;                                   \
1442                   else                                                        \
1443                     count_leading_zeros (cnt, quot);                          \
1444                   exponent -= cnt;                                            \
1445                   if (BITS_PER_MP_LIMB - cnt > MANT_DIG)                      \
1446                     {                                                         \
1447                       used = MANT_DIG + cnt;                                  \
1448                       retval[0] = quot >> (BITS_PER_MP_LIMB - used);          \
1449                       bits = MANT_DIG + 1;                                    \
1450                     }                                                         \
1451                   else                                                        \
1452                     {                                                         \
1453                       /* Note that we only clear the second element.  */      \
1454                       /* The conditional is determined at compile time.  */   \
1455                       if (RETURN_LIMB_SIZE > 1)                               \
1456                         retval[1] = 0;                                        \
1457                       retval[0] = quot;                                       \
1458                       bits = -cnt;                                            \
1459                     }                                                         \
1460                 }                                                             \
1461               else if (bits + BITS_PER_MP_LIMB <= MANT_DIG)                   \
1462                 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, BITS_PER_MP_LIMB,   \
1463                                 quot);                                        \
1464               else                                                            \
1465                 {                                                             \
1466                   used = MANT_DIG - bits;                                     \
1467                   if (used > 0)                                               \
1468                     __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, used, quot);    \
1469                 }                                                             \
1470               bits += BITS_PER_MP_LIMB
1471
1472               got_limb;
1473             }
1474           while (bits <= MANT_DIG);
1475
1476           return round_and_return (retval, exponent - 1, negative,
1477                                    quot, BITS_PER_MP_LIMB - 1 - used,
1478                                    more_bits || n != 0);
1479         }
1480       case 2:
1481         {
1482           mp_limb_t d0, d1, n0, n1;
1483           mp_limb_t quot = 0;
1484           int used = 0;
1485
1486           d0 = den[0];
1487           d1 = den[1];
1488
1489           if (numsize < densize)
1490             {
1491               if (num[0] >= d1)
1492                 {
1493                   /* The numerator of the number occupies fewer bits than
1494                      the denominator but the one limb is bigger than the
1495                      high limb of the numerator.  */
1496                   n1 = 0;
1497                   n0 = num[0];
1498                 }
1499               else
1500                 {
1501                   if (bits <= 0)
1502                     exponent -= BITS_PER_MP_LIMB;
1503                   else
1504                     {
1505                       if (bits + BITS_PER_MP_LIMB <= MANT_DIG)
1506                         __mpn_lshift_1 (retval, RETURN_LIMB_SIZE,
1507                                         BITS_PER_MP_LIMB, 0);
1508                       else
1509                         {
1510                           used = MANT_DIG - bits;
1511                           if (used > 0)
1512                             __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, used, 0);
1513                         }
1514                       bits += BITS_PER_MP_LIMB;
1515                     }
1516                   n1 = num[0];
1517                   n0 = 0;
1518                 }
1519             }
1520           else
1521             {
1522               n1 = num[1];
1523               n0 = num[0];
1524             }
1525
1526           while (bits <= MANT_DIG)
1527             {
1528               mp_limb_t r;
1529
1530               if (n1 == d1)
1531                 {
1532                   /* QUOT should be either 111..111 or 111..110.  We need
1533                      special treatment of this rare case as normal division
1534                      would give overflow.  */
1535                   quot = ~(mp_limb_t) 0;
1536
1537                   r = n0 + d1;
1538                   if (r < d1)   /* Carry in the addition?  */
1539                     {
1540                       add_ssaaaa (n1, n0, r - d0, 0, 0, d0);
1541                       goto have_quot;
1542                     }
1543                   n1 = d0 - (d0 != 0);
1544                   n0 = -d0;
1545                 }
1546               else
1547                 {
1548                   udiv_qrnnd (quot, r, n1, n0, d1);
1549                   umul_ppmm (n1, n0, d0, quot);
1550                 }
1551
1552             q_test:
1553               if (n1 > r || (n1 == r && n0 > 0))
1554                 {
1555                   /* The estimated QUOT was too large.  */
1556                   --quot;
1557
1558                   sub_ddmmss (n1, n0, n1, n0, 0, d0);
1559                   r += d1;
1560                   if (r >= d1)  /* If not carry, test QUOT again.  */
1561                     goto q_test;
1562                 }
1563               sub_ddmmss (n1, n0, r, 0, n1, n0);
1564
1565             have_quot:
1566               got_limb;
1567             }
1568
1569           return round_and_return (retval, exponent - 1, negative,
1570                                    quot, BITS_PER_MP_LIMB - 1 - used,
1571                                    more_bits || n1 != 0 || n0 != 0);
1572         }
1573       default:
1574         {
1575           int i;
1576           mp_limb_t cy, dX, d1, n0, n1;
1577           mp_limb_t quot = 0;
1578           int used = 0;
1579
1580           dX = den[densize - 1];
1581           d1 = den[densize - 2];
1582
1583           /* The division does not work if the upper limb of the two-limb
1584              numerator is greater than the denominator.  */
1585           if (__mpn_cmp (num, &den[densize - numsize], numsize) > 0)
1586             num[numsize++] = 0;
1587
1588           if (numsize < densize)
1589             {
1590               mp_size_t empty = densize - numsize;
1591               register int i;
1592
1593               if (bits <= 0)
1594                 exponent -= empty * BITS_PER_MP_LIMB;
1595               else
1596                 {
1597                   if (bits + empty * BITS_PER_MP_LIMB <= MANT_DIG)
1598                     {
1599                       /* We make a difference here because the compiler
1600                          cannot optimize the `else' case that good and
1601                          this reflects all currently used FLOAT types
1602                          and GMP implementations.  */
1603 #if RETURN_LIMB_SIZE <= 2
1604                       assert (empty == 1);
1605                       __mpn_lshift_1 (retval, RETURN_LIMB_SIZE,
1606                                       BITS_PER_MP_LIMB, 0);
1607 #else
1608                       for (i = RETURN_LIMB_SIZE - 1; i >= empty; --i)
1609                         retval[i] = retval[i - empty];
1610                       while (i >= 0)
1611                         retval[i--] = 0;
1612 #endif
1613                     }
1614                   else
1615                     {
1616                       used = MANT_DIG - bits;
1617                       if (used >= BITS_PER_MP_LIMB)
1618                         {
1619                           register int i;
1620                           (void) __mpn_lshift (&retval[used
1621                                                        / BITS_PER_MP_LIMB],
1622                                                retval,
1623                                                (RETURN_LIMB_SIZE
1624                                                 - used / BITS_PER_MP_LIMB),
1625                                                used % BITS_PER_MP_LIMB);
1626                           for (i = used / BITS_PER_MP_LIMB - 1; i >= 0; --i)
1627                             retval[i] = 0;
1628                         }
1629                       else if (used > 0)
1630                         __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, used, 0);
1631                     }
1632                   bits += empty * BITS_PER_MP_LIMB;
1633                 }
1634               for (i = numsize; i > 0; --i)
1635                 num[i + empty] = num[i - 1];
1636               MPN_ZERO (num, empty + 1);
1637             }
1638           else
1639             {
1640               int i;
1641               assert (numsize == densize);
1642               for (i = numsize; i > 0; --i)
1643                 num[i] = num[i - 1];
1644               num[0] = 0;
1645             }
1646
1647           den[densize] = 0;
1648           n0 = num[densize];
1649
1650           while (bits <= MANT_DIG)
1651             {
1652               if (n0 == dX)
1653                 /* This might over-estimate QUOT, but it's probably not
1654                    worth the extra code here to find out.  */
1655                 quot = ~(mp_limb_t) 0;
1656               else
1657                 {
1658                   mp_limb_t r;
1659
1660                   udiv_qrnnd (quot, r, n0, num[densize - 1], dX);
1661                   umul_ppmm (n1, n0, d1, quot);
1662
1663                   while (n1 > r || (n1 == r && n0 > num[densize - 2]))
1664                     {
1665                       --quot;
1666                       r += dX;
1667                       if (r < dX) /* I.e. "carry in previous addition?" */
1668                         break;
1669                       n1 -= n0 < d1;
1670                       n0 -= d1;
1671                     }
1672                 }
1673
1674               /* Possible optimization: We already have (q * n0) and (1 * n1)
1675                  after the calculation of QUOT.  Taking advantage of this, we
1676                  could make this loop make two iterations less.  */
1677
1678               cy = __mpn_submul_1 (num, den, densize + 1, quot);
1679
1680               if (num[densize] != cy)
1681                 {
1682                   cy = __mpn_add_n (num, num, den, densize);
1683                   assert (cy != 0);
1684                   --quot;
1685                 }
1686               n0 = num[densize] = num[densize - 1];
1687               for (i = densize - 1; i > 0; --i)
1688                 num[i] = num[i - 1];
1689               num[0] = 0;
1690
1691               got_limb;
1692             }
1693
1694           for (i = densize; num[i] == 0 && i >= 0; --i)
1695             ;
1696           return round_and_return (retval, exponent - 1, negative,
1697                                    quot, BITS_PER_MP_LIMB - 1 - used,
1698                                    more_bits || i >= 0);
1699         }
1700       }
1701   }
1702
1703   /* NOTREACHED */
1704 }
1705 #if defined _LIBC && !defined USE_WIDE_CHAR
1706 libc_hidden_def (____STRTOF_INTERNAL)
1707 #endif
1708 \f
1709 /* External user entry point.  */
1710
1711 FLOAT
1712 #ifdef weak_function
1713 weak_function
1714 #endif
1715 __STRTOF (nptr, endptr, loc)
1716      const STRING_TYPE *nptr;
1717      STRING_TYPE **endptr;
1718      __locale_t loc;
1719 {
1720   return ____STRTOF_INTERNAL (nptr, endptr, 0, loc);
1721 }
1722 #if defined _LIBC
1723 libc_hidden_def (__STRTOF)
1724 libc_hidden_ver (__STRTOF, STRTOF)
1725 #endif
1726 weak_alias (__STRTOF, STRTOF)
1727
1728 #ifdef LONG_DOUBLE_COMPAT
1729 # if LONG_DOUBLE_COMPAT(libc, GLIBC_2_1)
1730 #  ifdef USE_WIDE_CHAR
1731 compat_symbol (libc, __wcstod_l, __wcstold_l, GLIBC_2_1);
1732 #  else
1733 compat_symbol (libc, __strtod_l, __strtold_l, GLIBC_2_1);
1734 #  endif
1735 # endif
1736 # if LONG_DOUBLE_COMPAT(libc, GLIBC_2_3)
1737 #  ifdef USE_WIDE_CHAR
1738 compat_symbol (libc, wcstod_l, wcstold_l, GLIBC_2_3);
1739 #  else
1740 compat_symbol (libc, strtod_l, strtold_l, GLIBC_2_3);
1741 #  endif
1742 # endif
1743 #endif