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 license given in the file "LICENSE"
6 * distributed in the NASM archive.
8 * initial version 13/ix/96 by Simon Tatham
28 static bool daz = false; /* denormals as zero */
29 static enum float_round rc = FLOAT_RC_NEAR; /* rounding control */
37 /* "A limb is like a digit but bigger */
38 typedef uint32_t fp_limb;
39 typedef uint64_t fp_2limb;
42 #define LIMB_BYTES (LIMB_BITS/8)
43 #define LIMB_TOP_BIT ((fp_limb)1 << (LIMB_BITS-1))
44 #define LIMB_MASK ((fp_limb)(~0))
45 #define LIMB_ALL_BYTES ((fp_limb)0x01010101)
46 #define LIMB_BYTE(x) ((x)*LIMB_ALL_BYTES)
49 #define put(a,b) (*(uint32_t *)(a) = (b))
51 #define put(a,b) (((a)[0] = (b)), \
52 ((a)[1] = (b) >> 8), \
53 ((a)[2] = (b) >> 16), \
57 /* 112 bits + 64 bits for accuracy + 16 bits for rounding */
60 /* 52 digits fit in 176 bits because 10^53 > 2^176 > 10^52 */
61 #define MANT_DIGITS 52
63 /* the format and the argument list depend on MANT_LIMBS */
64 #define MANT_FMT "%08x_%08x_%08x_%08x_%08x_%08x"
65 #define MANT_ARG SOME_ARG(mant, 0)
67 #define SOME_ARG(a,i) (a)[(i)+0], (a)[(i)+1], (a)[(i)+2], (a)[(i)+3], \
68 (a)[(i)+4], (a)[(i)+5]
71 * ---------------------------------------------------------------------------
72 * emit a printf()-like debug message... but only if DEBUG_FLOAT was defined
73 * ---------------------------------------------------------------------------
77 #define dprintf(x) printf x
79 #define dprintf(x) do { } while (0)
83 * ---------------------------------------------------------------------------
85 * ---------------------------------------------------------------------------
87 static int float_multiply(fp_limb *to, fp_limb *from)
89 fp_2limb temp[MANT_LIMBS * 2];
93 * guaranteed that top bit of 'from' is set -- so we only have
94 * to worry about _one_ bit shift to the left
96 dprintf(("%s=" MANT_FMT "\n", "mul1", SOME_ARG(to, 0)));
97 dprintf(("%s=" MANT_FMT "\n", "mul2", SOME_ARG(from, 0)));
99 memset(temp, 0, sizeof temp);
101 for (i = 0; i < MANT_LIMBS; i++) {
102 for (j = 0; j < MANT_LIMBS; j++) {
104 n = (fp_2limb) to[i] * (fp_2limb) from[j];
105 temp[i + j] += n >> LIMB_BITS;
106 temp[i + j + 1] += (fp_limb)n;
110 for (i = MANT_LIMBS * 2; --i;) {
111 temp[i - 1] += temp[i] >> LIMB_BITS;
112 temp[i] &= LIMB_MASK;
115 dprintf(("%s=" MANT_FMT "_" MANT_FMT "\n", "temp", SOME_ARG(temp, 0),
116 SOME_ARG(temp, MANT_LIMBS)));
118 if (temp[0] & LIMB_TOP_BIT) {
119 for (i = 0; i < MANT_LIMBS; i++) {
120 to[i] = temp[i] & LIMB_MASK;
122 dprintf(("%s=" MANT_FMT " (%i)\n", "prod", SOME_ARG(to, 0), 0));
125 for (i = 0; i < MANT_LIMBS; i++) {
126 to[i] = (temp[i] << 1) + !!(temp[i + 1] & LIMB_TOP_BIT);
128 dprintf(("%s=" MANT_FMT " (%i)\n", "prod", SOME_ARG(to, 0), -1));
134 * ---------------------------------------------------------------------------
135 * read an exponent; returns INT32_MAX on error
136 * ---------------------------------------------------------------------------
138 static int32_t read_exponent(const char *string, int32_t max)
143 if (*string == '+') {
145 } else if (*string == '-') {
150 if (*string >= '0' && *string <= '9') {
151 i = (i * 10) + (*string - '0');
154 * To ensure that underflows and overflows are
155 * handled properly we must avoid wraparounds of
156 * the signed integer value that is used to hold
157 * the exponent. Therefore we cap the exponent at
158 * +/-5000, which is slightly more/less than
159 * what's required for normal and denormal numbers
160 * in single, double, and extended precision, but
161 * sufficient to avoid signed integer wraparound.
165 } else if (*string == '_') {
168 error(ERR_NONFATAL|ERR_PASS1,
169 "invalid character in floating-point constant %s: '%c'",
170 "exponent", *string);
180 * ---------------------------------------------------------------------------
182 * ---------------------------------------------------------------------------
184 static bool ieee_flconvert(const char *string, fp_limb *mant,
187 char digits[MANT_DIGITS];
189 fp_limb mult[MANT_LIMBS], bit;
191 int32_t tenpwr, twopwr;
193 bool started, seendot, warned;
198 started = seendot = false;
200 while (*string && *string != 'E' && *string != 'e') {
201 if (*string == '.') {
205 error(ERR_NONFATAL|ERR_PASS1,
206 "too many periods in floating-point constant");
209 } else if (*string >= '0' && *string <= '9') {
210 if (*string == '0' && !started) {
216 if (p < digits + sizeof(digits)) {
217 *p++ = *string - '0';
220 error(ERR_WARNING|ERR_WARN_FL_TOOLONG|ERR_PASS1,
221 "floating-point constant significand contains "
222 "more than %i digits", MANT_DIGITS);
230 } else if (*string == '_') {
233 error(ERR_NONFATAL|ERR_PASS1,
234 "invalid character in floating-point constant %s: '%c'",
235 "significand", *string);
244 string++; /* eat the E */
245 e = read_exponent(string, 5000);
252 * At this point, the memory interval [digits,p) contains a
253 * series of decimal digits zzzzzzz, such that our number X
254 * satisfies X = 0.zzzzzzz * 10^tenpwr.
259 dprintf(("%c", *q + '0'));
262 dprintf((" * 10^%i\n", tenpwr));
265 * Now convert [digits,p) to our internal representation.
268 for (m = mant; m < mant + MANT_LIMBS; m++) {
275 while (m < mant + MANT_LIMBS) {
277 while (p > q && !p[-1]) {
283 for (r = p; r-- > q;) {
312 * At this point, the 'mant' array contains the first frac-
313 * tional places of a base-2^16 real number which when mul-
314 * tiplied by 2^twopwr and 5^tenpwr gives X.
316 dprintf(("X = " MANT_FMT " * 2^%i * 5^%i\n", MANT_ARG, twopwr,
320 * Now multiply 'mant' by 5^tenpwr.
322 if (tenpwr < 0) { /* mult = 5^-1 = 0.2 */
323 for (m = mult; m < mult + MANT_LIMBS - 1; m++) {
324 *m = LIMB_BYTE(0xcc);
326 mult[MANT_LIMBS - 1] = LIMB_BYTE(0xcc)+1;
331 * If tenpwr was 1000...000b, then it becomes 1000...000b. See
332 * the "ANSI C" comment below for more details on that case.
334 * Because we already truncated tenpwr to +5000...-5000 inside
335 * the exponent parsing code, this shouldn't happen though.
337 } else if (tenpwr > 0) { /* mult = 5^+1 = 5.0 */
338 mult[0] = (fp_limb)5 << (LIMB_BITS-3); /* 0xA000... */
339 for (m = mult + 1; m < mult + MANT_LIMBS; m++) {
347 dprintf(("loop=" MANT_FMT " * 2^%i * 5^%i (%i)\n", MANT_ARG,
348 twopwr, tenpwr, extratwos));
350 dprintf(("mant*mult\n"));
351 twopwr += extratwos + float_multiply(mant, mult);
353 dprintf(("mult*mult\n"));
354 extratwos = extratwos * 2 + float_multiply(mult, mult);
358 * In ANSI C, the result of right-shifting a signed integer is
359 * considered implementation-specific. To ensure that the loop
360 * terminates even if tenpwr was 1000...000b to begin with, we
361 * manually clear the MSB, in case a 1 was shifted in.
363 * Because we already truncated tenpwr to +5000...-5000 inside
364 * the exponent parsing code, this shouldn't matter; neverthe-
365 * less it is the right thing to do here.
367 tenpwr &= (uint32_t) - 1 >> 1;
371 * At this point, the 'mant' array contains the first frac-
372 * tional places of a base-2^16 real number in [0.5,1) that
373 * when multiplied by 2^twopwr gives X. Or it contains zero
374 * of course. We are done.
381 * ---------------------------------------------------------------------------
382 * operations of specific bits
383 * ---------------------------------------------------------------------------
386 /* Set a bit, using *bigendian* bit numbering (0 = MSB) */
387 static void set_bit(fp_limb *mant, int bit)
389 mant[bit/LIMB_BITS] |= LIMB_TOP_BIT >> (bit & (LIMB_BITS-1));
392 /* Test a single bit */
393 static int test_bit(const fp_limb *mant, int bit)
395 return (mant[bit/LIMB_BITS] >> (~bit & (LIMB_BITS-1))) & 1;
398 /* Report if the mantissa value is all zero */
399 static bool is_zero(const fp_limb *mant)
403 for (i = 0; i < MANT_LIMBS; i++)
411 * ---------------------------------------------------------------------------
412 * round a mantissa off after i words
413 * ---------------------------------------------------------------------------
416 #define ROUND_COLLECT_BITS \
418 m = mant[i] & (2*bit-1); \
419 for (j = i+1; j < MANT_LIMBS; j++) \
423 #define ROUND_ABS_DOWN \
425 mant[i] &= ~(bit-1); \
426 for (j = i+1; j < MANT_LIMBS; j++) \
431 #define ROUND_ABS_UP \
433 mant[i] = (mant[i] & ~(bit-1)) + bit; \
434 for (j = i+1; j < MANT_LIMBS; j++) \
436 while (i > 0 && !mant[i]) \
441 static bool ieee_round(bool minus, fp_limb *mant, int bits)
445 int i = bits / LIMB_BITS;
446 int p = bits % LIMB_BITS;
447 fp_limb bit = LIMB_TOP_BIT >> p;
449 if (rc == FLOAT_RC_NEAR) {
457 if (test_bit(mant, bits-1)) {
466 } else if (rc == FLOAT_RC_ZERO ||
467 rc == (minus ? FLOAT_RC_UP : FLOAT_RC_DOWN)) {
470 /* rc == (minus ? FLOAT_RC_DOWN : FLOAT_RC_UP) */
471 /* Round toward +/- infinity */
482 /* Returns a value >= 16 if not a valid hex digit */
483 static unsigned int hexval(char c)
485 unsigned int v = (unsigned char) c;
487 if (v >= '0' && v <= '9')
490 return (v|0x20) - 'a' + 10;
493 /* Handle floating-point numbers with radix 2^bits and binary exponent */
494 static bool ieee_flconvert_bin(const char *string, int bits,
495 fp_limb *mant, int32_t *exponent)
497 static const int log2tbl[16] =
498 { -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3 };
499 fp_limb mult[MANT_LIMBS + 1], *mp;
502 bool seendot, seendigit;
504 int radix = 1 << bits;
508 seendot = seendigit = false;
512 memset(mult, 0, sizeof mult);
514 while ((c = *string++) != '\0') {
519 error(ERR_NONFATAL|ERR_PASS1,
520 "too many periods in floating-point constant");
523 } else if ((v = hexval(c)) < (unsigned int)radix) {
524 if (!seendigit && v) {
529 ms = (LIMB_BITS-1)-l;
531 twopwr = seendot ? twopwr-bits+l : l+1-bits;
538 if (mp > &mult[MANT_LIMBS])
539 mp = &mult[MANT_LIMBS]; /* Guard slot */
551 } else if (c == 'p' || c == 'P') {
553 e = read_exponent(string, 20000);
558 } else if (c == '_') {
561 error(ERR_NONFATAL|ERR_PASS1,
562 "floating-point constant: `%c' is invalid character", c);
568 memset(mant, 0, sizeof mult); /* Zero */
571 memcpy(mant, mult, sizeof mult);
579 * Shift a mantissa to the right by i bits.
581 static void ieee_shr(fp_limb *mant, int i)
587 sr = i % LIMB_BITS; sl = LIMB_BITS-sr;
592 for (j = MANT_LIMBS-1; j >= offs; j--)
593 mant[j] = mant[j-offs];
595 n = mant[MANT_LIMBS-1-offs] >> sr;
596 for (j = MANT_LIMBS-1; j > offs; j--) {
598 mant[j] = (m << sl) | n;
607 /* Produce standard IEEE formats, with implicit or explicit integer
608 bit; this makes the following assumptions:
610 - the sign bit is the MSB, followed by the exponent,
611 followed by the integer bit if present.
612 - the sign bit plus exponent fit in 16 bits.
613 - the exponent bias is 2^(n-1)-1 for an n-bit exponent */
617 int mantissa; /* Fractional bits in the mantissa */
618 int explicit; /* Explicit integer */
619 int exponent; /* Bits in the exponent */
623 * The 16- and 128-bit formats are expected to be in IEEE 754r.
624 * AMD SSE5 uses the 16-bit format.
626 * The 32- and 64-bit formats are the original IEEE 754 formats.
628 * The 80-bit format is x87-specific, but widely used.
630 * The 8-bit format appears to be the consensus 8-bit floating-point
631 * format. It is apparently used in graphics applications.
633 static const struct ieee_format ieee_8 = { 1, 3, 0, 4 };
634 static const struct ieee_format ieee_16 = { 2, 10, 0, 5 };
635 static const struct ieee_format ieee_32 = { 4, 23, 0, 8 };
636 static const struct ieee_format ieee_64 = { 8, 52, 0, 11 };
637 static const struct ieee_format ieee_80 = { 10, 63, 1, 15 };
638 static const struct ieee_format ieee_128 = { 16, 112, 0, 15 };
640 /* Types of values we can generate */
650 static int to_float(const char *str, int s, uint8_t * result,
651 const struct ieee_format *fmt)
653 fp_limb mant[MANT_LIMBS], *mp, m;
654 int32_t exponent = 0;
655 int32_t expmax = 1 << (fmt->exponent - 1);
656 fp_limb one_mask = LIMB_TOP_BIT >>
657 ((fmt->exponent+fmt->explicit) % LIMB_BITS);
658 int one_pos = (fmt->exponent+fmt->explicit)/LIMB_BITS;
664 int bits = fmt->bytes * 8;
670 case 'n': /* __nan__ */
672 case 'q': /* __qnan__ */
676 case 's': /* __snan__ */
680 case 'i': /* __infinity__ */
685 error(ERR_NONFATAL|ERR_PASS1,
686 "internal error: unknown FP constant token `%s'\n", str);
695 ok = ieee_flconvert_bin(str+2, 4, mant, &exponent);
699 ok = ieee_flconvert_bin(str+2, 3, mant, &exponent);
703 ok = ieee_flconvert_bin(str+2, 1, mant, &exponent);
707 ok = ieee_flconvert(str+2, mant, &exponent);
710 /* Leading zero was just a zero? */
711 ok = ieee_flconvert(str, mant, &exponent);
714 } else if (str[0] == '$') {
715 ok = ieee_flconvert_bin(str+1, 4, mant, &exponent);
717 ok = ieee_flconvert(str, mant, &exponent);
722 } else if (mant[0] & LIMB_TOP_BIT) {
727 if (exponent >= 2 - expmax && exponent <= expmax) {
729 } else if (exponent > 0) {
731 error(ERR_WARNING|ERR_WARN_FL_OVERFLOW|ERR_PASS1,
732 "overflow in floating-point constant");
735 /* underflow or denormal; the denormal code handles
748 memset(mant, 0, sizeof mant);
753 shift = -(exponent + expmax - 2 - fmt->exponent)
755 ieee_shr(mant, shift);
756 ieee_round(minus, mant, bits);
757 if (mant[one_pos] & one_mask) {
758 /* One's position is set, we rounded up into normal range */
761 mant[one_pos] &= ~one_mask; /* remove explicit one */
762 mant[0] |= exponent << (LIMB_BITS-1 - fmt->exponent);
764 if (daz || is_zero(mant)) {
765 /* Flush denormals to zero */
766 error(ERR_WARNING|ERR_WARN_FL_UNDERFLOW|ERR_PASS1,
767 "underflow in floating-point constant");
770 error(ERR_WARNING|ERR_WARN_FL_DENORM|ERR_PASS1,
771 "denormal floating-point constant");
778 exponent += expmax - 1;
779 ieee_shr(mant, fmt->exponent+fmt->explicit);
780 ieee_round(minus, mant, bits);
781 /* did we scale up by one? */
782 if (test_bit(mant, fmt->exponent+fmt->explicit-1)) {
785 if (exponent >= (expmax << 1)-1) {
786 error(ERR_WARNING|ERR_WARN_FL_OVERFLOW|ERR_PASS1,
787 "overflow in floating-point constant");
794 mant[one_pos] &= ~one_mask; /* remove explicit one */
795 mant[0] |= exponent << (LIMB_BITS-1 - fmt->exponent);
802 memset(mant, 0, sizeof mant);
803 mant[0] = (((fp_limb)1 << fmt->exponent)-1)
804 << (LIMB_BITS-1 - fmt->exponent);
806 mant[one_pos] |= one_mask;
808 set_bit(mant, fmt->exponent+fmt->explicit+1);
809 else if (type == FL_SNAN)
810 set_bit(mant, fmt->exponent+fmt->explicit+fmt->mantissa);
814 mant[0] |= minus ? LIMB_TOP_BIT : 0;
816 m = mant[fmt->bytes/LIMB_BYTES];
817 for (i = LIMB_BYTES-(fmt->bytes % LIMB_BYTES); i < LIMB_BYTES; i++)
818 *result++ = m >> (i*8);
820 for (mp = &mant[fmt->bytes/LIMB_BYTES], i = 0;
821 i < fmt->bytes; i += LIMB_BYTES) {
824 result += LIMB_BYTES;
827 return 1; /* success */
830 int float_const(const char *number, int sign, uint8_t * result,
831 int bytes, efunc err)
837 return to_float(number, sign, result, &ieee_8);
839 return to_float(number, sign, result, &ieee_16);
841 return to_float(number, sign, result, &ieee_32);
843 return to_float(number, sign, result, &ieee_64);
845 return to_float(number, sign, result, &ieee_80);
847 return to_float(number, sign, result, &ieee_128);
849 error(ERR_PANIC, "strange value %d passed to float_const", bytes);
854 /* Set floating-point options */
855 int float_option(const char *option)
857 if (!nasm_stricmp(option, "daz")) {
860 } else if (!nasm_stricmp(option, "nodaz")) {
863 } else if (!nasm_stricmp(option, "near")) {
866 } else if (!nasm_stricmp(option, "down")) {
869 } else if (!nasm_stricmp(option, "up")) {
872 } else if (!nasm_stricmp(option, "zero")) {
875 } else if (!nasm_stricmp(option, "default")) {
880 return -1; /* Unknown option */