Refactor floating-point formatting code; fix 80-bit denorms
[nasm.git] / float.c
blob6db5fba6c2ba0c44658e8120c73fe84b80b54a53
1 /* float.c floating-point constant support for the Netwide Assembler
3 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4 * Julian Hall. All rights reserved. The software is
5 * redistributable under the licence given in the file "Licence"
6 * distributed in the NASM archive.
8 * initial version 13/ix/96 by Simon Tatham
9 */
11 #include "compiler.h"
13 #include <ctype.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <inttypes.h>
19 #include "nasm.h"
20 #include "float.h"
23 * -----------------
24 * local variables
25 * -----------------
27 static efunc error;
28 static bool daz = false; /* denormals as zero */
29 static enum float_round rc = FLOAT_RC_NEAR; /* rounding control */
32 * -----------
33 * constants
34 * -----------
37 /* 112 bits + 64 bits for accuracy + 16 bits for rounding */
38 #define MANT_WORDS 12
40 /* 52 digits fit in 176 bits because 10^53 > 2^176 > 10^52 */
41 #define MANT_DIGITS 52
43 /* the format and the argument list depend on MANT_WORDS */
44 #define MANT_FMT "%04x%04x_%04x%04x_%04x%04x_%04x%04x_%04x%04x_%04x%04x"
45 #define MANT_ARG SOME_ARG(mant, 0)
47 #define SOME_ARG(a,i) (a)[(i)+0], (a)[(i)+1], (a)[(i)+2], (a)[(i)+3], \
48 (a)[(i)+4], (a)[(i)+5], (a)[(i)+6], (a)[(i)+7], (a)[(i)+8], \
49 (a)[(i)+9], (a)[(i)+10], (a)[(i)+11]
52 * ---------------------------------------------------------------------------
53 * emit a printf()-like debug message... but only if DEBUG_FLOAT was defined
54 * ---------------------------------------------------------------------------
57 #ifdef DEBUG_FLOAT
58 #define dprintf(x) printf x
59 #else /* */
60 #define dprintf(x) do { } while (0)
61 #endif /* */
64 * ---------------------------------------------------------------------------
65 * multiply
66 * ---------------------------------------------------------------------------
68 static int float_multiply(uint16_t * to, uint16_t * from)
70 uint32_t temp[MANT_WORDS * 2];
71 int32_t i, j;
73 /*
74 * guaranteed that top bit of 'from' is set -- so we only have
75 * to worry about _one_ bit shift to the left
77 dprintf(("%s=" MANT_FMT "\n", "mul1", SOME_ARG(to, 0)));
78 dprintf(("%s=" MANT_FMT "\n", "mul2", SOME_ARG(from, 0)));
80 memset(temp, 0, sizeof temp);
82 for (i = 0; i < MANT_WORDS; i++) {
83 for (j = 0; j < MANT_WORDS; j++) {
84 uint32_t n;
85 n = (uint32_t) to[i] * (uint32_t) from[j];
86 temp[i + j] += n >> 16;
87 temp[i + j + 1] += n & 0xFFFF;
91 for (i = MANT_WORDS * 2; --i;) {
92 temp[i - 1] += temp[i] >> 16;
93 temp[i] &= 0xFFFF;
96 dprintf(("%s=" MANT_FMT "_" MANT_FMT "\n", "temp", SOME_ARG(temp, 0),
97 SOME_ARG(temp, MANT_WORDS)));
99 if (temp[0] & 0x8000) {
100 for (i = 0; i < MANT_WORDS; i++) {
101 to[i] = temp[i] & 0xFFFF;
103 dprintf(("%s=" MANT_FMT " (%i)\n", "prod", SOME_ARG(to, 0), 0));
104 return 0;
105 } else {
106 for (i = 0; i < MANT_WORDS; i++) {
107 to[i] = (temp[i] << 1) + !!(temp[i + 1] & 0x8000);
109 dprintf(("%s=" MANT_FMT " (%i)\n", "prod", SOME_ARG(to, 0), -1));
110 return -1;
115 * ---------------------------------------------------------------------------
116 * convert
117 * ---------------------------------------------------------------------------
119 static bool ieee_flconvert(const char *string, uint16_t * mant,
120 int32_t * exponent)
122 char digits[MANT_DIGITS];
123 char *p, *q, *r;
124 uint16_t mult[MANT_WORDS], bit;
125 uint16_t *m;
126 int32_t tenpwr, twopwr;
127 int32_t extratwos;
128 bool started, seendot, warned;
129 p = digits;
130 tenpwr = 0;
131 started = seendot = warned = false;
132 while (*string && *string != 'E' && *string != 'e') {
133 if (*string == '.') {
134 if (!seendot) {
135 seendot = true;
136 } else {
137 error(ERR_NONFATAL,
138 "too many periods in floating-point constant");
139 return false;
141 } else if (*string >= '0' && *string <= '9') {
142 if (*string == '0' && !started) {
143 if (seendot) {
144 tenpwr--;
146 } else {
147 started = true;
148 if (p < digits + sizeof(digits)) {
149 *p++ = *string - '0';
150 } else {
151 if (!warned) {
152 error(ERR_WARNING,
153 "floating-point constant significand contains "
154 "more than %i digits", MANT_DIGITS);
155 warned = true;
158 if (!seendot) {
159 tenpwr++;
162 } else if (*string == '_') {
164 /* do nothing */
165 } else {
166 error(ERR_NONFATAL,
167 "invalid character in floating-point constant %s: '%c'",
168 "significand", *string);
169 return false;
171 string++;
173 if (*string) {
174 int32_t i = 0;
175 bool neg = false;
176 string++; /* eat the E */
177 if (*string == '+') {
178 string++;
179 } else if (*string == '-') {
180 neg = true;
181 string++;
183 while (*string) {
184 if (*string >= '0' && *string <= '9') {
185 i = (i * 10) + (*string - '0');
188 * To ensure that underflows and overflows are
189 * handled properly we must avoid wraparounds of
190 * the signed integer value that is used to hold
191 * the exponent. Therefore we cap the exponent at
192 * +/-5000, which is slightly more/less than
193 * what's required for normal and denormal numbers
194 * in single, double, and extended precision, but
195 * sufficient to avoid signed integer wraparound.
197 if (i > 5000) {
198 break;
200 } else if (*string == '_') {
202 /* do nothing */
203 } else {
204 error(ERR_NONFATAL,
205 "invalid character in floating-point constant %s: '%c'",
206 "exponent", *string);
207 return false;
209 string++;
211 if (neg) {
212 i = 0 - i;
214 tenpwr += i;
218 * At this point, the memory interval [digits,p) contains a
219 * series of decimal digits zzzzzzz, such that our number X
220 * satisfies X = 0.zzzzzzz * 10^tenpwr.
222 q = digits;
223 dprintf(("X = 0."));
224 while (q < p) {
225 dprintf(("%c", *q + '0'));
226 q++;
228 dprintf((" * 10^%i\n", tenpwr));
231 * Now convert [digits,p) to our internal representation.
233 bit = 0x8000;
234 for (m = mant; m < mant + MANT_WORDS; m++) {
235 *m = 0;
237 m = mant;
238 q = digits;
239 started = false;
240 twopwr = 0;
241 while (m < mant + MANT_WORDS) {
242 uint16_t carry = 0;
243 while (p > q && !p[-1]) {
244 p--;
246 if (p <= q) {
247 break;
249 for (r = p; r-- > q;) {
250 int32_t i;
251 i = 2 * *r + carry;
252 if (i >= 10) {
253 carry = 1;
254 i -= 10;
255 } else {
256 carry = 0;
258 *r = i;
260 if (carry) {
261 *m |= bit;
262 started = true;
264 if (started) {
265 if (bit == 1) {
266 bit = 0x8000;
267 m++;
268 } else {
269 bit >>= 1;
271 } else {
272 twopwr--;
275 twopwr += tenpwr;
278 * At this point, the 'mant' array contains the first frac-
279 * tional places of a base-2^16 real number which when mul-
280 * tiplied by 2^twopwr and 5^tenpwr gives X.
282 dprintf(("X = " MANT_FMT " * 2^%i * 5^%i\n", MANT_ARG, twopwr,
283 tenpwr));
286 * Now multiply 'mant' by 5^tenpwr.
288 if (tenpwr < 0) { /* mult = 5^-1 = 0.2 */
289 for (m = mult; m < mult + MANT_WORDS - 1; m++) {
290 *m = 0xCCCC;
292 mult[MANT_WORDS - 1] = 0xCCCD;
293 extratwos = -2;
294 tenpwr = -tenpwr;
297 * If tenpwr was 1000...000b, then it becomes 1000...000b. See
298 * the "ANSI C" comment below for more details on that case.
300 * Because we already truncated tenpwr to +5000...-5000 inside
301 * the exponent parsing code, this shouldn't happen though.
303 } else if (tenpwr > 0) { /* mult = 5^+1 = 5.0 */
304 mult[0] = 0xA000;
305 for (m = mult + 1; m < mult + MANT_WORDS; m++) {
306 *m = 0;
308 extratwos = 3;
309 } else {
310 extratwos = 0;
312 while (tenpwr) {
313 dprintf(("loop=" MANT_FMT " * 2^%i * 5^%i (%i)\n", MANT_ARG,
314 twopwr, tenpwr, extratwos));
315 if (tenpwr & 1) {
316 dprintf(("mant*mult\n"));
317 twopwr += extratwos + float_multiply(mant, mult);
319 dprintf(("mult*mult\n"));
320 extratwos = extratwos * 2 + float_multiply(mult, mult);
321 tenpwr >>= 1;
324 * In ANSI C, the result of right-shifting a signed integer is
325 * considered implementation-specific. To ensure that the loop
326 * terminates even if tenpwr was 1000...000b to begin with, we
327 * manually clear the MSB, in case a 1 was shifted in.
329 * Because we already truncated tenpwr to +5000...-5000 inside
330 * the exponent parsing code, this shouldn't matter; neverthe-
331 * less it is the right thing to do here.
333 tenpwr &= (uint32_t) - 1 >> 1;
337 * At this point, the 'mant' array contains the first frac-
338 * tional places of a base-2^16 real number in [0.5,1) that
339 * when multiplied by 2^twopwr gives X. Or it contains zero
340 * of course. We are done.
342 *exponent = twopwr;
343 return true;
347 * ---------------------------------------------------------------------------
348 * round a mantissa off after i words
349 * ---------------------------------------------------------------------------
352 #define ROUND_COLLECT_BITS \
353 for (j = i; j < MANT_WORDS; j++) { \
354 m = m | mant[j]; \
357 #define ROUND_ABS_DOWN \
358 for (j = i; j < MANT_WORDS; j++) { \
359 mant[j] = 0x0000; \
362 #define ROUND_ABS_UP \
363 do { \
364 ++mant[--i]; \
365 mant[i] &= 0xFFFF; \
366 } while (i > 0 && !mant[i]); \
367 return (!i && !mant[i]);
369 static bool ieee_round(int sign, uint16_t * mant, int32_t i)
371 uint16_t m = 0;
372 int32_t j;
373 if ((sign == 0x0000) || (sign == 0x8000)) {
374 if (rc == FLOAT_RC_NEAR) {
375 if (mant[i] & 0x8000) {
376 mant[i] &= 0x7FFF;
377 ROUND_COLLECT_BITS;
378 mant[i] |= 0x8000;
379 if (m) {
380 ROUND_ABS_UP;
381 } else {
382 if (mant[i - 1] & 1) {
383 ROUND_ABS_UP;
384 } else {
385 ROUND_ABS_DOWN;
388 } else {
389 ROUND_ABS_DOWN;
391 } else if (((sign == 0x0000) && (rc == FLOAT_RC_DOWN))
392 || ((sign == 0x8000) && (rc == FLOAT_RC_UP))) {
393 ROUND_COLLECT_BITS;
394 if (m) {
395 ROUND_ABS_DOWN;
397 } else if (((sign == 0x0000) && (rc == FLOAT_RC_UP))
398 || ((sign == 0x8000) && (rc == FLOAT_RC_DOWN))) {
399 ROUND_COLLECT_BITS;
400 if (m) {
401 ROUND_ABS_UP;
403 } else if (rc == FLOAT_RC_ZERO) {
404 ROUND_ABS_DOWN;
405 } else {
406 error(ERR_PANIC, "float_round() can't handle rc=%i", rc);
408 } else {
409 error(ERR_PANIC, "float_round() can't handle sign=%i", sign);
411 return false;
414 static int hexval(char c)
416 if (c >= '0' && c <= '9')
417 return c - '0';
418 else if (c >= 'a' && c <= 'f')
419 return c - 'a' + 10;
420 else
421 return c - 'A' + 10;
424 static bool ieee_flconvert_hex(const char *string, uint16_t * mant,
425 int32_t * exponent)
427 static const int log2tbl[16] =
428 { -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3 };
429 uint16_t mult[MANT_WORDS + 1], *mp;
430 int ms;
431 int32_t twopwr;
432 int seendot, seendigit;
433 unsigned char c;
435 twopwr = 0;
436 seendot = seendigit = 0;
437 ms = 0;
438 mp = NULL;
440 memset(mult, 0, sizeof mult);
442 while ((c = *string++) != '\0') {
443 if (c == '.') {
444 if (!seendot)
445 seendot = true;
446 else {
447 error(ERR_NONFATAL,
448 "too many periods in floating-point constant");
449 return false;
451 } else if (isxdigit(c)) {
452 int v = hexval(c);
454 if (!seendigit && v) {
455 int l = log2tbl[v];
457 seendigit = 1;
458 mp = mult;
459 ms = 15 - l;
461 twopwr = seendot ? twopwr - 4 + l : l - 3;
464 if (seendigit) {
465 if (ms <= 0) {
466 *mp |= v >> -ms;
467 mp++;
468 if (mp > &mult[MANT_WORDS])
469 mp = &mult[MANT_WORDS]; /* Guard slot */
470 ms += 16;
472 *mp |= v << ms;
473 ms -= 4;
475 if (!seendot)
476 twopwr += 4;
477 } else {
478 if (seendot)
479 twopwr -= 4;
481 } else if (c == 'p' || c == 'P') {
482 twopwr += atoi(string);
483 break;
484 } else {
485 error(ERR_NONFATAL,
486 "floating-point constant: `%c' is invalid character", c);
487 return false;
491 if (!seendigit) {
492 memset(mant, 0, 2 * MANT_WORDS); /* Zero */
493 *exponent = 0;
494 } else {
495 memcpy(mant, mult, 2 * MANT_WORDS);
496 *exponent = twopwr;
499 return true;
503 * Shift a mantissa to the right by i bits.
505 static void ieee_shr(uint16_t * mant, int i)
507 uint16_t n, m;
508 int j = 0;
509 int sr, sl, offs;
511 sr = i%16; sl = 16-sr;
512 offs = i/16;
514 if (sr == 0) {
515 if (offs)
516 for (j = MANT_WORDS-1; j >= offs; j--)
517 mant[j] = mant[j-offs];
518 } else {
519 n = mant[MANT_WORDS-1-offs] >> sr;
520 for (j = MANT_WORDS-1; j > offs; j--) {
521 m = mant[j-offs-1];
522 mant[j] = (m << sl) | n;
523 n = m >> sr;
525 mant[j--] = n;
527 while (j >= 0)
528 mant[j--] = 0;
531 #if defined(__i386__) || defined(__x86_64__)
532 #define put(a,b) (*(uint16_t *)(a) = (b))
533 #else
534 #define put(a,b) (((a)[0] = (b)), ((a)[1] = (b) >> 8))
535 #endif
537 /* Set a bit, using *bigendian* bit numbering (0 = MSB) */
538 static void set_bit(uint16_t *mant, int bit)
540 mant[bit >> 4] |= 1 << (~bit & 15);
543 /* Test a single bit */
544 static int test_bit(uint16_t *mant, int bit)
546 return (mant[bit >> 4] >> (~bit & 15)) & 1;
549 /* Produce standard IEEE formats, with implicit or explicit integer
550 bit; this makes the following assumptions:
552 - the sign bit is the MSB, followed by the exponent,
553 followed by the integer bit if present.
554 - the sign bit plus exponent fit in 16 bits.
555 - the exponent bias is 2^(n-1)-1 for an n-bit exponent */
557 struct ieee_format {
558 int words;
559 int mantissa; /* Fractional bits in the mantissa */
560 int explicit; /* Explicit integer */
561 int exponent; /* Bits in the exponent */
565 * The 16- and 128-bit formats are expected to be in IEEE 754r.
566 * AMD SSE5 uses the 16-bit format.
568 * The 32- and 64-bit formats are the original IEEE 754 formats.
570 * The 80-bit format is x87-specific, but widely used.
572 static const struct ieee_format ieee_16 = { 1, 10, 0, 5 };
573 static const struct ieee_format ieee_32 = { 2, 23, 0, 8 };
574 static const struct ieee_format ieee_64 = { 4, 52, 0, 11 };
575 static const struct ieee_format ieee_80 = { 5, 63, 1, 15 };
576 static const struct ieee_format ieee_128 = { 8, 112, 0, 15 };
578 /* Types of values we can generate */
579 enum floats {
580 FL_ZERO,
581 FL_DENORMAL,
582 FL_NORMAL,
583 FL_INFINITY,
584 FL_QNAN,
585 FL_SNAN
588 static int to_float(const char *str, int sign, uint8_t * result,
589 const struct ieee_format *fmt)
591 uint16_t mant[MANT_WORDS], *mp;
592 int32_t exponent = 0;
593 int32_t expmax = 1 << (fmt->exponent - 1);
594 uint16_t one_mask = 0x8000 >> ((fmt->exponent+fmt->explicit) % 16);
595 int one_pos = (fmt->exponent+fmt->explicit)/16;
596 int i;
597 int shift;
598 enum floats type;
599 bool ok;
601 sign = (sign < 0 ? 0x8000 : 0);
603 if (str[0] == '_') {
604 /* Special tokens */
606 switch (str[2]) {
607 case 'n': /* __nan__ */
608 case 'N':
609 case 'q': /* __qnan__ */
610 case 'Q':
611 type = FL_QNAN;
612 break;
613 case 's': /* __snan__ */
614 case 'S':
615 type = FL_SNAN;
616 break;
617 case 'i': /* __infinity__ */
618 case 'I':
619 type = FL_INFINITY;
620 break;
621 default:
622 error(ERR_NONFATAL,
623 "internal error: unknown FP constant token `%s'\n", str);
624 type = FL_QNAN;
625 break;
627 } else {
628 if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
629 ok = ieee_flconvert_hex(str + 2, mant, &exponent);
630 else
631 ok = ieee_flconvert(str, mant, &exponent);
633 if (!ok) {
634 type = FL_QNAN;
635 } else if (mant[0] & 0x8000) {
637 * Non-zero.
639 exponent--;
640 if (exponent >= 2 - expmax && exponent <= expmax) {
641 type = FL_NORMAL;
642 } else if (!daz && exponent < 2 - expmax &&
643 exponent >= 2 - expmax - fmt->mantissa) {
644 type = FL_DENORMAL;
645 } else if (exponent > 0) {
646 error(ERR_NONFATAL,
647 "overflow in floating-point constant");
648 type = FL_INFINITY;
649 } else {
650 /* underflow */
651 type = FL_ZERO;
653 } else {
654 /* Zero */
655 type = FL_ZERO;
659 switch (type) {
660 case FL_ZERO:
661 memset(mant, 0, sizeof mant);
662 break;
664 case FL_DENORMAL:
666 shift = -(exponent + expmax - 2 - fmt->exponent)
667 + fmt->explicit;
668 ieee_shr(mant, shift);
669 if (ieee_round(sign, mant, fmt->words)
670 || (shift > 0 && test_bit(mant, shift-1))) {
671 ieee_shr(mant, 1);
672 if (!shift) {
673 /* XXX: We shifted into the normal range? */
674 /* XXX: This is definitely not right... */
675 mant[0] |= 0x8000;
677 exponent++; /* UNUSED, WTF? */
679 break;
682 case FL_NORMAL:
683 exponent += expmax - 1;
684 ieee_shr(mant, fmt->exponent+fmt->explicit);
685 ieee_round(sign, mant, fmt->words);
686 /* did we scale up by one? */
687 if (test_bit(mant, fmt->exponent+fmt->explicit-1)) {
688 ieee_shr(mant, 1);
689 exponent++;
690 /* XXX: Handle overflow here */
693 if (!fmt->explicit)
694 mant[one_pos] &= ~one_mask; /* remove explicit one */
695 mant[0] |= exponent << (15 - fmt->exponent);
696 break;
698 case FL_INFINITY:
699 case FL_QNAN:
700 case FL_SNAN:
701 memset(mant, 0, sizeof mant);
702 mant[0] = ((1 << fmt->exponent)-1) << (15 - fmt->exponent);
703 if (fmt->explicit)
704 mant[one_pos] |= one_mask;
705 if (type == FL_QNAN)
706 set_bit(mant, fmt->exponent+fmt->explicit+1);
707 else if (type == FL_SNAN)
708 set_bit(mant, fmt->exponent+fmt->explicit+fmt->mantissa);
709 break;
712 mant[0] |= sign;
714 for (mp = &mant[fmt->words], i = 0; i < fmt->words; i++) {
715 uint16_t m = *--mp;
716 put(result, m);
717 result += 2;
720 return 1; /* success */
723 int float_const(const char *number, int32_t sign, uint8_t * result,
724 int bytes, efunc err)
726 error = err;
728 switch (bytes) {
729 case 2:
730 return to_float(number, sign, result, &ieee_16);
731 case 4:
732 return to_float(number, sign, result, &ieee_32);
733 case 8:
734 return to_float(number, sign, result, &ieee_64);
735 case 10:
736 return to_float(number, sign, result, &ieee_80);
737 case 16:
738 return to_float(number, sign, result, &ieee_128);
739 default:
740 error(ERR_PANIC, "strange value %d passed to float_const", bytes);
741 return 0;