NASM 0.99.05
[nasm/avx512.git] / float.c
blobec37775e29b59e322ea65bca1909ed02438e8d6c
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 = false;
132 warned = (pass0 != 1);
133 while (*string && *string != 'E' && *string != 'e') {
134 if (*string == '.') {
135 if (!seendot) {
136 seendot = true;
137 } else {
138 error(ERR_NONFATAL,
139 "too many periods in floating-point constant");
140 return false;
142 } else if (*string >= '0' && *string <= '9') {
143 if (*string == '0' && !started) {
144 if (seendot) {
145 tenpwr--;
147 } else {
148 started = true;
149 if (p < digits + sizeof(digits)) {
150 *p++ = *string - '0';
151 } else {
152 if (!warned) {
153 error(ERR_WARNING|ERR_WARN_FL_TOOLONG,
154 "floating-point constant significand contains "
155 "more than %i digits", MANT_DIGITS);
156 warned = true;
159 if (!seendot) {
160 tenpwr++;
163 } else if (*string == '_') {
165 /* do nothing */
166 } else {
167 error(ERR_NONFATAL,
168 "invalid character in floating-point constant %s: '%c'",
169 "significand", *string);
170 return false;
172 string++;
174 if (*string) {
175 int32_t i = 0;
176 bool neg = false;
177 string++; /* eat the E */
178 if (*string == '+') {
179 string++;
180 } else if (*string == '-') {
181 neg = true;
182 string++;
184 while (*string) {
185 if (*string >= '0' && *string <= '9') {
186 i = (i * 10) + (*string - '0');
189 * To ensure that underflows and overflows are
190 * handled properly we must avoid wraparounds of
191 * the signed integer value that is used to hold
192 * the exponent. Therefore we cap the exponent at
193 * +/-5000, which is slightly more/less than
194 * what's required for normal and denormal numbers
195 * in single, double, and extended precision, but
196 * sufficient to avoid signed integer wraparound.
198 if (i > 5000) {
199 break;
201 } else if (*string == '_') {
203 /* do nothing */
204 } else {
205 error(ERR_NONFATAL,
206 "invalid character in floating-point constant %s: '%c'",
207 "exponent", *string);
208 return false;
210 string++;
212 if (neg) {
213 i = 0 - i;
215 tenpwr += i;
219 * At this point, the memory interval [digits,p) contains a
220 * series of decimal digits zzzzzzz, such that our number X
221 * satisfies X = 0.zzzzzzz * 10^tenpwr.
223 q = digits;
224 dprintf(("X = 0."));
225 while (q < p) {
226 dprintf(("%c", *q + '0'));
227 q++;
229 dprintf((" * 10^%i\n", tenpwr));
232 * Now convert [digits,p) to our internal representation.
234 bit = 0x8000;
235 for (m = mant; m < mant + MANT_WORDS; m++) {
236 *m = 0;
238 m = mant;
239 q = digits;
240 started = false;
241 twopwr = 0;
242 while (m < mant + MANT_WORDS) {
243 uint16_t carry = 0;
244 while (p > q && !p[-1]) {
245 p--;
247 if (p <= q) {
248 break;
250 for (r = p; r-- > q;) {
251 int32_t i;
252 i = 2 * *r + carry;
253 if (i >= 10) {
254 carry = 1;
255 i -= 10;
256 } else {
257 carry = 0;
259 *r = i;
261 if (carry) {
262 *m |= bit;
263 started = true;
265 if (started) {
266 if (bit == 1) {
267 bit = 0x8000;
268 m++;
269 } else {
270 bit >>= 1;
272 } else {
273 twopwr--;
276 twopwr += tenpwr;
279 * At this point, the 'mant' array contains the first frac-
280 * tional places of a base-2^16 real number which when mul-
281 * tiplied by 2^twopwr and 5^tenpwr gives X.
283 dprintf(("X = " MANT_FMT " * 2^%i * 5^%i\n", MANT_ARG, twopwr,
284 tenpwr));
287 * Now multiply 'mant' by 5^tenpwr.
289 if (tenpwr < 0) { /* mult = 5^-1 = 0.2 */
290 for (m = mult; m < mult + MANT_WORDS - 1; m++) {
291 *m = 0xCCCC;
293 mult[MANT_WORDS - 1] = 0xCCCD;
294 extratwos = -2;
295 tenpwr = -tenpwr;
298 * If tenpwr was 1000...000b, then it becomes 1000...000b. See
299 * the "ANSI C" comment below for more details on that case.
301 * Because we already truncated tenpwr to +5000...-5000 inside
302 * the exponent parsing code, this shouldn't happen though.
304 } else if (tenpwr > 0) { /* mult = 5^+1 = 5.0 */
305 mult[0] = 0xA000;
306 for (m = mult + 1; m < mult + MANT_WORDS; m++) {
307 *m = 0;
309 extratwos = 3;
310 } else {
311 extratwos = 0;
313 while (tenpwr) {
314 dprintf(("loop=" MANT_FMT " * 2^%i * 5^%i (%i)\n", MANT_ARG,
315 twopwr, tenpwr, extratwos));
316 if (tenpwr & 1) {
317 dprintf(("mant*mult\n"));
318 twopwr += extratwos + float_multiply(mant, mult);
320 dprintf(("mult*mult\n"));
321 extratwos = extratwos * 2 + float_multiply(mult, mult);
322 tenpwr >>= 1;
325 * In ANSI C, the result of right-shifting a signed integer is
326 * considered implementation-specific. To ensure that the loop
327 * terminates even if tenpwr was 1000...000b to begin with, we
328 * manually clear the MSB, in case a 1 was shifted in.
330 * Because we already truncated tenpwr to +5000...-5000 inside
331 * the exponent parsing code, this shouldn't matter; neverthe-
332 * less it is the right thing to do here.
334 tenpwr &= (uint32_t) - 1 >> 1;
338 * At this point, the 'mant' array contains the first frac-
339 * tional places of a base-2^16 real number in [0.5,1) that
340 * when multiplied by 2^twopwr gives X. Or it contains zero
341 * of course. We are done.
343 *exponent = twopwr;
344 return true;
348 * ---------------------------------------------------------------------------
349 * round a mantissa off after i words
350 * ---------------------------------------------------------------------------
353 #define ROUND_COLLECT_BITS \
354 for (j = i; j < MANT_WORDS; j++) { \
355 m = m | mant[j]; \
358 #define ROUND_ABS_DOWN \
359 for (j = i; j < MANT_WORDS; j++) { \
360 mant[j] = 0x0000; \
363 #define ROUND_ABS_UP \
364 do { \
365 ++mant[--i]; \
366 mant[i] &= 0xFFFF; \
367 } while (i > 0 && !mant[i]); \
368 return (!i && !mant[i]);
370 static bool ieee_round(int sign, uint16_t * mant, int32_t i)
372 uint16_t m = 0;
373 int32_t j;
374 if ((sign == 0x0000) || (sign == 0x8000)) {
375 if (rc == FLOAT_RC_NEAR) {
376 if (mant[i] & 0x8000) {
377 mant[i] &= 0x7FFF;
378 ROUND_COLLECT_BITS;
379 mant[i] |= 0x8000;
380 if (m) {
381 ROUND_ABS_UP;
382 } else {
383 if (mant[i - 1] & 1) {
384 ROUND_ABS_UP;
385 } else {
386 ROUND_ABS_DOWN;
389 } else {
390 ROUND_ABS_DOWN;
392 } else if (((sign == 0x0000) && (rc == FLOAT_RC_DOWN))
393 || ((sign == 0x8000) && (rc == FLOAT_RC_UP))) {
394 ROUND_COLLECT_BITS;
395 if (m) {
396 ROUND_ABS_DOWN;
398 } else if (((sign == 0x0000) && (rc == FLOAT_RC_UP))
399 || ((sign == 0x8000) && (rc == FLOAT_RC_DOWN))) {
400 ROUND_COLLECT_BITS;
401 if (m) {
402 ROUND_ABS_UP;
404 } else if (rc == FLOAT_RC_ZERO) {
405 ROUND_ABS_DOWN;
406 } else {
407 error(ERR_PANIC, "float_round() can't handle rc=%i", rc);
409 } else {
410 error(ERR_PANIC, "float_round() can't handle sign=%i", sign);
412 return false;
415 static int hexval(char c)
417 if (c >= '0' && c <= '9')
418 return c - '0';
419 else if (c >= 'a' && c <= 'f')
420 return c - 'a' + 10;
421 else
422 return c - 'A' + 10;
425 static bool ieee_flconvert_hex(const char *string, uint16_t * mant,
426 int32_t * exponent)
428 static const int log2tbl[16] =
429 { -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3 };
430 uint16_t mult[MANT_WORDS + 1], *mp;
431 int ms;
432 int32_t twopwr;
433 int seendot, seendigit;
434 unsigned char c;
436 twopwr = 0;
437 seendot = seendigit = 0;
438 ms = 0;
439 mp = NULL;
441 memset(mult, 0, sizeof mult);
443 while ((c = *string++) != '\0') {
444 if (c == '.') {
445 if (!seendot)
446 seendot = true;
447 else {
448 error(ERR_NONFATAL,
449 "too many periods in floating-point constant");
450 return false;
452 } else if (isxdigit(c)) {
453 int v = hexval(c);
455 if (!seendigit && v) {
456 int l = log2tbl[v];
458 seendigit = 1;
459 mp = mult;
460 ms = 15 - l;
462 twopwr = seendot ? twopwr - 4 + l : l - 3;
465 if (seendigit) {
466 if (ms <= 0) {
467 *mp |= v >> -ms;
468 mp++;
469 if (mp > &mult[MANT_WORDS])
470 mp = &mult[MANT_WORDS]; /* Guard slot */
471 ms += 16;
473 *mp |= v << ms;
474 ms -= 4;
476 if (!seendot)
477 twopwr += 4;
478 } else {
479 if (seendot)
480 twopwr -= 4;
482 } else if (c == 'p' || c == 'P') {
483 twopwr += atoi(string);
484 break;
485 } else {
486 error(ERR_NONFATAL,
487 "floating-point constant: `%c' is invalid character", c);
488 return false;
492 if (!seendigit) {
493 memset(mant, 0, 2 * MANT_WORDS); /* Zero */
494 *exponent = 0;
495 } else {
496 memcpy(mant, mult, 2 * MANT_WORDS);
497 *exponent = twopwr;
500 return true;
504 * Shift a mantissa to the right by i bits.
506 static void ieee_shr(uint16_t * mant, int i)
508 uint16_t n, m;
509 int j = 0;
510 int sr, sl, offs;
512 sr = i%16; sl = 16-sr;
513 offs = i/16;
515 if (sr == 0) {
516 if (offs)
517 for (j = MANT_WORDS-1; j >= offs; j--)
518 mant[j] = mant[j-offs];
519 } else {
520 n = mant[MANT_WORDS-1-offs] >> sr;
521 for (j = MANT_WORDS-1; j > offs; j--) {
522 m = mant[j-offs-1];
523 mant[j] = (m << sl) | n;
524 n = m >> sr;
526 mant[j--] = n;
528 while (j >= 0)
529 mant[j--] = 0;
532 #if defined(__i386__) || defined(__x86_64__)
533 #define put(a,b) (*(uint16_t *)(a) = (b))
534 #else
535 #define put(a,b) (((a)[0] = (b)), ((a)[1] = (b) >> 8))
536 #endif
538 /* Set a bit, using *bigendian* bit numbering (0 = MSB) */
539 static void set_bit(uint16_t *mant, int bit)
541 mant[bit >> 4] |= 1 << (~bit & 15);
544 /* Test a single bit */
545 static int test_bit(const uint16_t *mant, int bit)
547 return (mant[bit >> 4] >> (~bit & 15)) & 1;
550 /* Report if the mantissa value is all zero */
551 static bool is_zero(const uint16_t *mant)
553 int i;
555 for (i = 0; i < MANT_WORDS; i++)
556 if (mant[i])
557 return false;
559 return true;
562 /* Produce standard IEEE formats, with implicit or explicit integer
563 bit; this makes the following assumptions:
565 - the sign bit is the MSB, followed by the exponent,
566 followed by the integer bit if present.
567 - the sign bit plus exponent fit in 16 bits.
568 - the exponent bias is 2^(n-1)-1 for an n-bit exponent */
570 struct ieee_format {
571 int words;
572 int mantissa; /* Fractional bits in the mantissa */
573 int explicit; /* Explicit integer */
574 int exponent; /* Bits in the exponent */
578 * The 16- and 128-bit formats are expected to be in IEEE 754r.
579 * AMD SSE5 uses the 16-bit format.
581 * The 32- and 64-bit formats are the original IEEE 754 formats.
583 * The 80-bit format is x87-specific, but widely used.
585 static const struct ieee_format ieee_16 = { 1, 10, 0, 5 };
586 static const struct ieee_format ieee_32 = { 2, 23, 0, 8 };
587 static const struct ieee_format ieee_64 = { 4, 52, 0, 11 };
588 static const struct ieee_format ieee_80 = { 5, 63, 1, 15 };
589 static const struct ieee_format ieee_128 = { 8, 112, 0, 15 };
591 /* Types of values we can generate */
592 enum floats {
593 FL_ZERO,
594 FL_DENORMAL,
595 FL_NORMAL,
596 FL_INFINITY,
597 FL_QNAN,
598 FL_SNAN
601 static int to_float(const char *str, int sign, uint8_t * result,
602 const struct ieee_format *fmt)
604 uint16_t mant[MANT_WORDS], *mp;
605 int32_t exponent = 0;
606 int32_t expmax = 1 << (fmt->exponent - 1);
607 uint16_t one_mask = 0x8000 >> ((fmt->exponent+fmt->explicit) % 16);
608 int one_pos = (fmt->exponent+fmt->explicit)/16;
609 int i;
610 int shift;
611 enum floats type;
612 bool ok;
614 sign = (sign < 0 ? 0x8000 : 0);
616 if (str[0] == '_') {
617 /* Special tokens */
619 switch (str[2]) {
620 case 'n': /* __nan__ */
621 case 'N':
622 case 'q': /* __qnan__ */
623 case 'Q':
624 type = FL_QNAN;
625 break;
626 case 's': /* __snan__ */
627 case 'S':
628 type = FL_SNAN;
629 break;
630 case 'i': /* __infinity__ */
631 case 'I':
632 type = FL_INFINITY;
633 break;
634 default:
635 error(ERR_NONFATAL,
636 "internal error: unknown FP constant token `%s'\n", str);
637 type = FL_QNAN;
638 break;
640 } else {
641 if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
642 ok = ieee_flconvert_hex(str + 2, mant, &exponent);
643 else
644 ok = ieee_flconvert(str, mant, &exponent);
646 if (!ok) {
647 type = FL_QNAN;
648 } else if (mant[0] & 0x8000) {
650 * Non-zero.
652 exponent--;
653 if (exponent >= 2 - expmax && exponent <= expmax) {
654 type = FL_NORMAL;
655 } else if (exponent < 2 - expmax &&
656 exponent >= 2 - expmax - fmt->mantissa) {
657 type = FL_DENORMAL;
658 } else if (exponent > 0) {
659 if (pass0 == 1)
660 error(ERR_WARNING|ERR_WARN_FL_OVERFLOW,
661 "overflow in floating-point constant");
662 type = FL_INFINITY;
663 } else {
664 /* underflow */
665 if (pass0 == 1)
666 error(ERR_WARNING|ERR_WARN_FL_UNDERFLOW,
667 "underflow in floating-point constant");
668 type = FL_ZERO;
670 } else {
671 /* Zero */
672 type = FL_ZERO;
676 switch (type) {
677 case FL_ZERO:
678 zero:
679 memset(mant, 0, sizeof mant);
680 break;
682 case FL_DENORMAL:
684 shift = -(exponent + expmax - 2 - fmt->exponent)
685 + fmt->explicit;
686 ieee_shr(mant, shift);
687 ieee_round(sign, mant, fmt->words);
688 if (mant[one_pos] & one_mask) {
689 /* One's position is set, we rounded up into normal range */
690 exponent = 1;
691 if (!fmt->explicit)
692 mant[one_pos] &= ~one_mask; /* remove explicit one */
693 mant[0] |= exponent << (15 - fmt->exponent);
694 } else {
695 if (daz || is_zero(mant)) {
696 /* Flush denormals to zero */
697 if (pass0 == 1)
698 error(ERR_WARNING|ERR_WARN_FL_UNDERFLOW,
699 "underflow in floating-point constant");
700 goto zero;
701 } else {
702 if (pass0 == 1)
703 error(ERR_WARNING|ERR_WARN_FL_DENORM,
704 "denormal floating-point constant");
707 break;
710 case FL_NORMAL:
711 exponent += expmax - 1;
712 ieee_shr(mant, fmt->exponent+fmt->explicit);
713 ieee_round(sign, mant, fmt->words);
714 /* did we scale up by one? */
715 if (test_bit(mant, fmt->exponent+fmt->explicit-1)) {
716 ieee_shr(mant, 1);
717 exponent++;
718 if (exponent >= (expmax << 1)-1) {
719 if (pass0 == 1)
720 error(ERR_WARNING|ERR_WARN_FL_OVERFLOW,
721 "overflow in floating-point constant");
722 type = FL_INFINITY;
723 goto overflow;
727 if (!fmt->explicit)
728 mant[one_pos] &= ~one_mask; /* remove explicit one */
729 mant[0] |= exponent << (15 - fmt->exponent);
730 break;
732 case FL_INFINITY:
733 case FL_QNAN:
734 case FL_SNAN:
735 overflow:
736 memset(mant, 0, sizeof mant);
737 mant[0] = ((1 << fmt->exponent)-1) << (15 - fmt->exponent);
738 if (fmt->explicit)
739 mant[one_pos] |= one_mask;
740 if (type == FL_QNAN)
741 set_bit(mant, fmt->exponent+fmt->explicit+1);
742 else if (type == FL_SNAN)
743 set_bit(mant, fmt->exponent+fmt->explicit+fmt->mantissa);
744 break;
747 mant[0] |= sign;
749 for (mp = &mant[fmt->words], i = 0; i < fmt->words; i++) {
750 uint16_t m = *--mp;
751 put(result, m);
752 result += 2;
755 return 1; /* success */
758 int float_const(const char *number, int32_t sign, uint8_t * result,
759 int bytes, efunc err)
761 error = err;
763 switch (bytes) {
764 case 2:
765 return to_float(number, sign, result, &ieee_16);
766 case 4:
767 return to_float(number, sign, result, &ieee_32);
768 case 8:
769 return to_float(number, sign, result, &ieee_64);
770 case 10:
771 return to_float(number, sign, result, &ieee_80);
772 case 16:
773 return to_float(number, sign, result, &ieee_128);
774 default:
775 error(ERR_PANIC, "strange value %d passed to float_const", bytes);
776 return 0;
780 /* Set floating-point options */
781 int float_option(const char *option)
783 if (!nasm_stricmp(option, "daz")) {
784 daz = true;
785 return 0;
786 } else if (!nasm_stricmp(option, "nodaz")) {
787 daz = false;
788 return 0;
789 } else if (!nasm_stricmp(option, "near")) {
790 rc = FLOAT_RC_NEAR;
791 return 0;
792 } else if (!nasm_stricmp(option, "down")) {
793 rc = FLOAT_RC_DOWN;
794 return 0;
795 } else if (!nasm_stricmp(option, "up")) {
796 rc = FLOAT_RC_UP;
797 return 0;
798 } else if (!nasm_stricmp(option, "zero")) {
799 rc = FLOAT_RC_ZERO;
800 return 0;
801 } else if (!nasm_stricmp(option, "default")) {
802 rc = FLOAT_RC_NEAR;
803 daz = false;
804 return 0;
805 } else {
806 return -1; /* Unknown option */