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