3 * File name: ir/tv/fltcalc.c
9 * Copyright: (c) 2003 Universität Karlsruhe
10 * Licence: This file protected by GPL - GNU GENERAL PUBLIC LICENSE.
22 #include <math.h> /* need isnan() and isinf() (will be changed)*/
23 /* undef some reused constants defined by math.h */
28 #ifdef HAVE_INTTYPES_H
29 # include <inttypes.h>
48 typedef uint32_t UINT32;
50 #ifdef HAVE_LONG_DOUBLE
51 #ifdef WORDS_BIGENDIAN
58 volatile long double d;
67 volatile long double d;
71 #ifdef WORDS_BIGENDIAN
91 * possible float states
94 NORMAL, /**< normal representation, implicit 1 */
96 SUBNORMAL, /**< denormals, implicit 0 */
98 NAN, /**< Not A Number */
101 /** A descriptor for an IEEE float value. */
103 unsigned char exponent_size; /**< size of exponent in bits */
104 unsigned char mantissa_size; /**< size of mantissa in bits */
105 value_class_t clss; /**< state of this float */
108 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
110 /* because variable sized structs are impossible, the internal
111 * value is represented as a pseudo-struct char array, addressed
114 * char sign; // 0 for positive, 1 for negative
115 * char exp[value_size];
116 * char mant[value_size];
120 #define _sign(a) (((char*)a)[SIGN_POS])
121 #define _exp(a) (&((char*)a)[EXPONENT_POS])
122 #define _mant(a) (&((char*)a)[MANTISSA_POS])
123 #define _desc(a) (*(descriptor_t *)&((char *)a)[DESCRIPTOR_POS])
125 #define _save_result(x) memcpy((x), sc_get_buffer(), value_size)
126 #define _shift_right(x, y, b) sc_shr((x), (y), value_size*4, 0, (b))
127 #define _shift_left(x, y, b) sc_shl((x), (y), value_size*4, 0, (b))
129 #define FC_DEFINE1(code) \
130 char *fc_##code(const void *a, void *result) { \
131 return _calc((const char*)a, NULL, FC_##code, (char*)result); \
134 #define FC_DEFINE2(code) \
135 char *fc_##code(const void *a, const void *b, void *result) { \
136 return _calc((const char*)a, (const char*)b, FC_##code, (char*)result); \
139 #define FUNC_PTR(code) fc_##code
142 # define DEBUGPRINTF(x) printf x
144 # define DEBUGPRINTF(x) ((void)0)
147 #if FLTCALC_TRACE_CALC
148 # define TRACEPRINTF(x) printf x
150 # define TRACEPRINTF(x) ((void)0)
153 static char *calc_buffer = NULL;
155 static fc_rounding_mode_t rounding_mode;
157 static int calc_buffer_size;
158 static int value_size;
160 static int EXPONENT_POS;
161 static int MANTISSA_POS;
162 static int DESCRIPTOR_POS;
164 static int max_precision;
169 static void _fail_char(const char *str, unsigned int len, int pos)
172 printf("ERROR: Unexpected character '%c'\n", *(str + pos));
174 printf("ERROR: Unexpected end of string\n");
175 while (len-- && *str) printf("%c", *str++); printf("\n");
176 while (pos--) printf(" "); printf("^\n");
177 /* the front end has to to check constant strings */
182 /** pack machine-like */
183 static char* _pack(const char *int_float, char *packed)
189 temp = alloca(value_size);
190 shift_val = alloca(value_size);
192 switch (_desc(int_float).clss) {
194 val_buffer = alloca(calc_buffer_size);
195 fc_get_qnan(_desc(int_float).exponent_size, _desc(int_float).mantissa_size, val_buffer);
196 int_float = val_buffer;
200 val_buffer = alloca(calc_buffer_size);
201 fc_get_plusinf(_desc(int_float).exponent_size, _desc(int_float).mantissa_size, val_buffer);
202 _sign(val_buffer) = _sign(int_float);
203 int_float = val_buffer;
210 sc_val_from_ulong(_sign(int_float), temp);
212 sc_val_from_ulong(_desc(int_float).exponent_size + _desc(int_float).mantissa_size, NULL);
213 _shift_left(temp, sc_get_buffer(), packed);
215 /* extract exponent */
216 sc_val_from_ulong(_desc(int_float).mantissa_size, shift_val);
218 _shift_left(_exp(int_float), shift_val, temp);
220 sc_or(temp, packed, packed);
222 /* extract mantissa */
223 /* remove 2 rounding bits */
224 sc_val_from_ulong(2, shift_val);
225 _shift_right(_mant(int_float), shift_val, temp);
227 /* remove leading 1 (or 0 if denormalized) */
228 sc_max_from_bits(_desc(int_float).mantissa_size, 0, shift_val); /* all mantissa bits are 1's */
229 sc_and(temp, shift_val, temp);
232 sc_or(temp, packed, packed);
237 char* _normalize(const char *in_val, char *out_val, int sticky)
240 char lsb, guard, round, round_dir = 0;
243 temp = alloca(value_size);
245 /* +2: save two rounding bits at the end */
246 hsb = 2 + _desc(in_val).mantissa_size - sc_get_highest_set_bit(_mant(in_val)) - 1;
248 if (in_val != out_val)
250 _sign(out_val) = _sign(in_val);
251 memcpy(&_desc(out_val), &_desc(in_val), sizeof(descriptor_t));
254 _desc(out_val).clss = NORMAL;
256 /* mantissa all zeros, so zero exponent (because of explicit one)*/
257 if (hsb == 2 + _desc(in_val).mantissa_size)
259 sc_val_from_ulong(0, _exp(out_val));
263 /* shift the first 1 into the left of the radix point (i.e. hsb == -1) */
267 sc_val_from_ulong(-hsb-1, temp);
269 _shift_right(_mant(in_val), temp, _mant(out_val));
271 /* remember if some bits were shifted away */
272 if (!sticky) sticky = sc_had_carry();
274 sc_add(_exp(in_val), temp, _exp(out_val));
279 sc_val_from_ulong(hsb+1, temp);
281 _shift_left(_mant(in_val), temp, _mant(out_val));
283 sc_sub(_exp(in_val), temp, _exp(out_val));
286 /* check for exponent underflow */
287 if (sc_is_negative(_exp(out_val)) || sc_is_zero(_exp(out_val))) {
288 DEBUGPRINTF(("Exponent underflow!\n"));
289 /* exponent underflow */
290 /* shift the mantissa right to have a zero exponent */
291 sc_val_from_ulong(1, temp);
292 sc_sub(temp, _exp(out_val), NULL);
294 _shift_right(_mant(out_val), sc_get_buffer(), _mant(out_val));
295 if (!sticky) sticky = sc_had_carry();
296 /* denormalized means exponent of zero */
297 sc_val_from_ulong(0, _exp(out_val));
299 _desc(out_val).clss = SUBNORMAL;
302 /* perform rounding by adding a value that clears the guard bit and the round bit
303 * and either causes a carry to round up or not */
304 /* get the last 3 bits of the value */
305 lsb = sc_sub_bits(_mant(out_val), _desc(out_val).mantissa_size + 2, 0) & 0x7;
306 guard = (lsb&0x2)>>1;
309 switch (rounding_mode)
312 /* round to nearest representable value, if in doubt choose the version
314 round_dir = guard && (sticky || round || lsb>>2);
317 /* if positive: round to one if the exact value is bigger, else to zero */
318 round_dir = (!_sign(out_val) && (guard || round || sticky));
321 /* if negative: round to one if the exact value is bigger, else to zero */
322 round_dir = (_sign(out_val) && (guard || round || sticky));
325 /* always round to 0 (chopping mode) */
329 DEBUGPRINTF(("Rounding (s%d, l%d, g%d, r%d, s%d) %s\n", _sign(out_val), lsb>>2, guard, round, sticky, (round_dir)?"up":"down"));
333 guard = (round^guard)<<1;
334 lsb = !(round || guard)<<2 | guard | round;
338 lsb = -((guard<<1) | round);
341 /* add the rounded value */
343 sc_val_from_long(lsb, temp);
344 sc_add(_mant(out_val), temp, _mant(out_val));
347 /* could have rounded down to zero */
348 if (sc_is_zero(_mant(out_val)) && (_desc(out_val).clss == SUBNORMAL))
349 _desc(out_val).clss = ZERO;
351 /* check for rounding overflow */
352 hsb = 2 + _desc(out_val).mantissa_size - sc_get_highest_set_bit(_mant(out_val)) - 1;
353 if ((_desc(out_val).clss != SUBNORMAL) && (hsb < -1))
355 sc_val_from_ulong(1, temp);
356 _shift_right(_mant(out_val), temp, _mant(out_val));
358 sc_add(_exp(out_val), temp, _exp(out_val));
360 else if ((_desc(out_val).clss == SUBNORMAL) && (hsb == -1))
362 /* overflow caused the mantissa to be normal again,
363 * so adapt the exponent accordingly */
364 sc_val_from_ulong(1, temp);
365 sc_add(_exp(out_val), temp, _exp(out_val));
367 _desc(out_val).clss = NORMAL;
369 /* no further rounding is needed, because rounding overflow means
370 * the carry of the original rounding was propagated all the way
371 * up to the bit left of the radix point. This implies the bits
372 * to the right are all zeros (rounding is +1) */
374 /* check for exponent overflow */
375 sc_val_from_ulong((1 << _desc(out_val).exponent_size) - 1, temp);
376 if (sc_comp(_exp(out_val), temp) != -1) {
377 DEBUGPRINTF(("Exponent overflow!\n"));
378 /* exponent overflow, reaction depends on rounding method:
380 * mode | sign of value | result
381 *--------------------------------------------------------------
382 * TO_NEAREST | + | +inf
384 *--------------------------------------------------------------
385 * TO_POSITIVE | + | +inf
386 * | - | smallest representable value
387 *--------------------------------------------------------------
388 * TO_NEAGTIVE | + | largest representable value
390 *--------------------------------------------------------------
391 * TO_ZERO | + | largest representable value
392 * | - | smallest representable value
393 *--------------------------------------------------------------*/
394 if (_sign(out_val) == 0)
396 /* value is positive */
397 switch (rounding_mode) {
400 _desc(out_val).clss = INF;
405 fc_get_max(_desc(out_val).exponent_size, _desc(out_val).mantissa_size, out_val);
408 /* value is negative */
409 switch (rounding_mode) {
412 _desc(out_val).clss = INF;
417 fc_get_min(_desc(out_val).exponent_size, _desc(out_val).mantissa_size, out_val);
426 * Operations involving NaN's must return NaN
428 #define handle_NAN(a, b, result) \
430 if (_desc(a).clss == NAN) { \
431 if (a != result) memcpy(result, a, calc_buffer_size); \
434 if (_desc(b).clss == NAN) { \
435 if (b != result) memcpy(result, b, calc_buffer_size); \
442 * calculate a + b, where a is the value with the bigger exponent
444 static char* _fadd(const char* a, const char* b, char* result)
452 handle_NAN(a, b, result);
454 /* make sure result has a descriptor */
455 if (result != a && result != b)
456 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
458 /* determine if this is an addition or subtraction */
459 sign = _sign(a) ^ _sign(b);
461 /* produce NaN on inf - inf */
462 if (sign && (_desc(a).clss == INF) && (_desc(b).clss == INF))
463 return fc_get_qnan(_desc(a).exponent_size, _desc(b).mantissa_size, result);
465 temp = alloca(value_size);
466 exp_diff = alloca(value_size);
468 /* get exponent difference */
469 sc_sub(_exp(a), _exp(b), exp_diff);
471 /* initially set sign to be the sign of a, special treatment of subtraction
472 * when exponents are equal is required though.
473 * Also special care about the sign is needed when the mantissas are equal
475 if (sign && sc_val_to_long(exp_diff) == 0) {
476 switch (sc_comp(_mant(a), _mant(b))) {
478 _sign(result) = _sign(a); /* abs(a) is bigger and a is negative */
481 _sign(result) = (rounding_mode == FC_TONEGATIVE);
484 _sign(result) = _sign(b); /* abs(b) is bigger and b is negative */
487 /* can't be reached */
492 _sign(result) = _sign(a);
494 /* sign has been taken care of, check for special cases */
495 if (_desc(a).clss == ZERO) {
496 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
499 if (_desc(b).clss == ZERO) {
500 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
504 if (_desc(a).clss == INF) {
505 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
508 if (_desc(b).clss == INF) {
509 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
513 /* shift the smaller value to the right to align the radix point */
514 /* subnormals have their radix point shifted to the right,
515 * take care of this first */
516 if ((_desc(b).clss == SUBNORMAL) && (_desc(a).clss != SUBNORMAL))
518 sc_val_from_ulong(1, temp);
519 sc_sub(exp_diff, temp, exp_diff);
522 _shift_right(_mant(b), exp_diff, temp);
523 sticky = sc_had_carry();
527 /* if subtracting a little more than the represented value or adding a little
528 * more than the represented value to a negative value this, in addition to the
529 * still set sticky bit, takes account of the 'little more' */
530 char *temp1 = alloca(calc_buffer_size);
531 sc_val_from_ulong(1, temp1);
532 sc_add(temp, temp1, temp);
536 if (sc_comp(_mant(a), temp) == -1)
537 sc_sub(temp, _mant(a), _mant(result));
539 sc_sub(_mant(a), temp, _mant(result));
541 sc_add(_mant(a), temp, _mant(result));
544 /* _normalize expects a 'normal' radix point, adding two subnormals
545 * results in a subnormal radix point -> shifting before normalizing */
546 if ((_desc(a).clss == SUBNORMAL) && (_desc(b).clss == SUBNORMAL))
548 sc_val_from_ulong(1, NULL);
549 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
552 /* resulting exponent is the bigger one */
553 memmove(_exp(result), _exp(a), value_size);
555 return _normalize(result, result, sticky);
561 static char* _fmul(const char* a, const char* b, char* result)
565 handle_NAN(a, b, result);
567 temp = alloca(value_size);
569 if (result != a && result != b)
570 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
572 _sign(result) = _sign(a) ^ _sign(b);
574 /* produce NaN on 0 * inf */
575 if (_desc(a).clss == ZERO) {
576 if (_desc(b).clss == INF)
577 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
579 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
582 if (_desc(b).clss == ZERO) {
583 if (_desc(a).clss == INF)
584 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
586 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-1);
590 if (_desc(a).clss == INF) {
591 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
594 if (_desc(b).clss == INF) {
595 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-1);
599 /* exp = exp(a) + exp(b) - excess */
600 sc_add(_exp(a), _exp(b), _exp(result));
602 sc_val_from_ulong((1<<_desc(a).exponent_size)/2-1, temp);
603 sc_sub(_exp(result), temp, _exp(result));
605 /* mixed normal, subnormal values introduce an error of 1, correct it */
606 if ((_desc(a).clss == SUBNORMAL) ^ (_desc(b).clss == SUBNORMAL))
608 sc_val_from_ulong(1, temp);
609 sc_add(_exp(result), temp, _exp(result));
612 sc_mul(_mant(a), _mant(b), _mant(result));
614 /* realign result: after a multiplication the digits right of the radix
615 * point are the sum of the factors' digits after the radix point. As all
616 * values are normalized they both have the same amount of these digits,
617 * which has to be restored by proper shifting
618 * +2 because of the two rounding bits */
619 sc_val_from_ulong(2 + _desc(result).mantissa_size, temp);
621 _shift_right(_mant(result), temp, _mant(result));
623 return _normalize(result, result, sc_had_carry());
629 static char* _fdiv(const char* a, const char* b, char* result)
631 char *temp, *dividend;
633 handle_NAN(a, b, result);
635 temp = alloca(value_size);
636 dividend = alloca(value_size);
638 if (result != a && result != b)
639 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
641 _sign(result) = _sign(a) ^ _sign(b);
643 /* produce nan on 0/0 and inf/inf */
644 if (_desc(a).clss == ZERO) {
645 if (_desc(b).clss == ZERO)
647 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
650 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
654 if (_desc(b).clss == INF) {
655 if (_desc(a).clss == INF)
657 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
660 sc_val_from_ulong(0, NULL);
661 _save_result(_exp(result));
662 _save_result(_mant(result));
663 _desc(result).clss = ZERO;
668 if (_desc(a).clss == INF) {
670 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
673 if (_desc(b).clss == ZERO) {
674 /* division by zero */
676 fc_get_minusinf(_desc(a).exponent_size, _desc(a).mantissa_size, result);
678 fc_get_plusinf(_desc(a).exponent_size, _desc(a).mantissa_size, result);
682 /* exp = exp(a) - exp(b) + excess - 1*/
683 sc_sub(_exp(a), _exp(b), _exp(result));
684 sc_val_from_ulong((1 << _desc(a).exponent_size)/2-2, temp);
685 sc_add(_exp(result), temp, _exp(result));
687 /* mixed normal, subnormal values introduce an error of 1, correct it */
688 if ((_desc(a).clss == SUBNORMAL) ^ (_desc(b).clss == SUBNORMAL))
690 sc_val_from_ulong(1, temp);
691 sc_add(_exp(result), temp, _exp(result));
694 /* mant(res) = mant(a) / 1/2mant(b) */
695 /* to gain more bits of precision in the result the dividend could be
696 * shifted left, as this operation does not loose bits. This would not
697 * fit into the integer precision, but due to the rounding bits (which
698 * are always zero because the values are all normalized) the divisor
699 * can be shifted right instead to achieve the same result */
700 sc_val_from_ulong(2 + _desc(result).mantissa_size, temp);
702 _shift_left(_mant(a), temp, dividend);
705 char *divisor = alloca(calc_buffer_size);
706 sc_val_from_ulong(1, divisor);
707 _shift_right(_mant(b), divisor, divisor);
708 sc_div(dividend, divisor, _mant(result));
711 return _normalize(result, result, sc_had_carry());
715 static void _power_of_ten(int exp, descriptor_t *desc, char *result)
723 /* set new descriptor (else result is supposed to already have one) */
725 memcpy(&_desc(result), desc, sizeof(descriptor_t));
727 build = alloca(value_size);
728 temp = alloca(value_size);
730 sc_val_from_ulong((1 << _desc(result).exponent_size)/2-1, _exp(result));
734 /* temp is value of ten now */
735 sc_val_from_ulong(10, NULL);
738 for (exp--; exp > 0; exp--) {
740 sc_mul(build, temp, NULL);
744 /* temp is amount of left shift needed to put the value left of the radix point */
745 sc_val_from_ulong(_desc(result).mantissa_size + 2, temp);
747 _shift_left(build, temp, _mant(result));
749 _normalize(result, result, 0);
755 * Truncate the fractional part away.
757 * This does not clip to any integer rang.
759 static char* _trunc(const char *a, char *result)
762 * When exponent == 0 all bits left of the radix point
763 * are the integral part of the value. For 15bit exp_size
764 * this would require a left shift of max. 16383 bits which
766 * But it is enough to ensure that no bit right of the radix
767 * point remains set. This restricts the interesting
768 * exponents to the interval [0, mant_size-1].
769 * Outside this interval the truncated value is either 0 or
770 * it does not have fractional parts.
773 int exp_bias, exp_val;
776 temp = alloca(value_size);
779 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
781 exp_bias = (1<<_desc(a).exponent_size)/2-1;
782 exp_val = sc_val_to_long(_exp(a)) - exp_bias;
785 sc_val_from_ulong(0, NULL);
786 _save_result(_exp(result));
787 _save_result(_mant(result));
788 _desc(result).clss = ZERO;
793 if (exp_val > _desc(a).mantissa_size) {
795 memcpy(result, a, calc_buffer_size);
800 /* set up a proper mask to delete all bits right of the
801 * radix point if the mantissa had been shifted until exp == 0 */
802 sc_max_from_bits(1 + exp_val, 0, temp);
803 sc_val_from_long(_desc(a).mantissa_size - exp_val + 2, NULL);
804 _shift_left(temp, sc_get_buffer(), temp);
806 /* and the mask and return the result */
807 sc_and(_mant(a), temp, _mant(result));
809 if (a != result) memcpy(_exp(result), _exp(a), value_size);
815 * This does value sanity checking(or should do it), sets up any prerequisites,
816 * calls the proper internal functions, clears up and returns
819 char* _calc(const char *a, const char *b, int opcode, char *result)
822 #ifdef FLTCALC_TRACE_CALC
825 buffer = alloca(100);
828 if (result == NULL) result = calc_buffer;
830 TRACEPRINTF(("%s ", fc_print(a, buffer, 100, FC_PACKED)));
834 /* make the value with the bigger exponent the first one */
835 TRACEPRINTF(("+ %s ", fc_print(b, buffer, 100, FC_PACKED)));
836 if (sc_comp(_exp(a), _exp(b)) == -1)
842 TRACEPRINTF(("- %s ", fc_print(b, buffer, 100, FC_PACKED)));
843 temp = alloca(calc_buffer_size);
844 memcpy(temp, b, calc_buffer_size);
845 _sign(temp) = !_sign(b);
846 if (sc_comp(_exp(a), _exp(temp)) == -1)
847 _fadd(temp, a, result);
849 _fadd(a, temp, result);
852 TRACEPRINTF(("* %s ", fc_print(b, buffer, 100, FC_PACKED)));
856 TRACEPRINTF(("/ %s ", fc_print(b, buffer, 100, FC_PACKED)));
860 TRACEPRINTF(("negated "));
861 if (a != result) memcpy(result, a, calc_buffer_size);
862 _sign(result) = !_sign(a);
865 TRACEPRINTF(("truncated to integer "));
869 TRACEPRINTF(("rounded to integer "));
874 TRACEPRINTF(("= %s\n", fc_print(result, buffer, 100, FC_PACKED)));
879 * functions defined in fltcalc.h
881 const void *fc_get_buffer(void)
886 int fc_get_buffer_length(void)
888 return calc_buffer_size;
891 char* fc_val_from_str(const char *str, unsigned int len, char exp_size, char mant_size, char *result)
904 int exp_int, hsb, state;
909 char *mant_str, *exp_val, *power_val;
911 if (result == NULL) result = calc_buffer;
913 exp_val = alloca(value_size);
914 power_val = alloca(calc_buffer_size);
915 mant_str = alloca((len)?(len):(strlen(str)));
917 _desc(result).exponent_size = exp_size;
918 _desc(result).mantissa_size = mant_size;
919 _desc(result).clss = NORMAL;
926 while (len == 0 || str-old_str < len)
943 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
950 state = RIGHT_OF_DOT;
961 _fail_char(old_str, len, str - old_str);
967 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
968 mant_str[pos++] = *(str++);
972 state = RIGHT_OF_DOT;
983 mant_str[pos] = '\0';
987 _fail_char(old_str, len, str - old_str);
993 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
994 mant_str[pos++] = *(str++);
1005 mant_str[pos] = '\0';
1009 _fail_char(old_str, len, str - old_str);
1019 if (*(str-1) != 'e' && *(str-1) != 'E') _fail_char(old_str, len, str - old_str);
1023 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
1024 mant_str[pos] = '\0';
1031 _fail_char(old_str, len, str - old_str);
1037 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
1042 case '\0': goto done;
1045 _fail_char(old_str, len, str - old_str);
1048 } /* switch(state) */
1051 sc_val_from_str(mant_str, strlen(mant_str), _mant(result));
1053 /* shift to put value left of radix point */
1054 sc_val_from_ulong(mant_size + 2, exp_val);
1056 _shift_left(_mant(result), exp_val, _mant(result));
1058 sc_val_from_ulong((1 << exp_size)/2-1, _exp(result));
1060 _normalize(result, result, 0);
1062 if (state == EXPONENT) {
1063 exp_int -= atoi(str-pos);
1066 _power_of_ten(exp_int, &_desc(result), power_val);
1068 _fdiv(result, power_val, result);
1073 /* XXX excuse of an implementation to make things work */
1075 #ifdef HAVE_LONG_DOUBLE
1076 val = strtold(str, NULL);
1078 val = strtod(str, NULL);
1081 DEBUGPRINTF(("val_from_str(%s)\n", str));
1082 return fc_val_from_float(val, exp_size, mant_size, result);
1086 char* fc_val_from_float(LLDBL l, char exp_size, char mant_size, char* result)
1089 int bias_res, bias_val, mant_val;
1091 UINT32 sign, exponent, mantissa0, mantissa1;
1094 bias_res = ((1<<exp_size)/2-1);
1096 #ifdef HAVE_LONG_DOUBLE
1099 sign = (srcval.val.high & 0x00008000) != 0;
1100 exponent = (srcval.val.high & 0x00007FFF) ;
1101 mantissa0 = srcval.val.mid;
1102 mantissa1 = srcval.val.low;
1103 #else /* no long double */
1106 sign = (srcval.val.high & 0x80000000) != 0;
1107 exponent = (srcval.val.high & 0x7FF00000) >> 20;
1108 mantissa0 = srcval.val.high & 0x000FFFFF;
1109 mantissa1 = srcval.val.low;
1112 #ifdef HAVE_LONG_DOUBLE
1113 TRACEPRINTF(("val_from_float(%.8X%.8X%.8X)\n", ((int*)&l)[2], ((int*)&l)[1], ((int*)&l)[0]));/* srcval.val.high, srcval.val.mid, srcval.val.low)); */
1114 DEBUGPRINTF(("(%d-%.4X-%.8X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1116 TRACEPRINTF(("val_from_float(%.8X%.8X)\n", srcval.val.high, srcval.val.low));
1117 DEBUGPRINTF(("(%d-%.3X-%.5X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1120 if (result == NULL) result = calc_buffer;
1121 temp = alloca(value_size);
1123 _desc(result).exponent_size = exp_size;
1124 _desc(result).mantissa_size = mant_size;
1127 _sign(result) = sign;
1129 /* sign and flag suffice to identify nan or inf, no exponent/mantissa
1130 * encoding is needed. the function can return immediately in these cases */
1132 _desc(result).clss = NAN;
1133 TRACEPRINTF(("val_from_float resulted in NAN\n"));
1136 else if (isinf(l)) {
1137 _desc(result).clss = INF;
1138 TRACEPRINTF(("val_from_float resulted in %sINF\n", (_sign(result)==1)?"-":""));
1142 /* build exponent, because input and output exponent and mantissa sizes may differ
1143 * this looks more complicated than it is: unbiased input exponent + output bias,
1144 * minus the mantissa difference which is added again later when the output float
1145 * becomes normalized */
1146 #ifdef HAVE_EXPLICIT_ONE
1147 sc_val_from_long((exponent-bias_val+bias_res)-(mant_val-mant_size-1), _exp(result));
1149 sc_val_from_long((exponent-bias_val+bias_res)-(mant_val-mant_size), _exp(result));
1152 /* build mantissa representation */
1153 #ifndef HAVE_EXPLICIT_ONE
1156 /* insert the hidden bit */
1157 sc_val_from_ulong(1, temp);
1158 sc_val_from_ulong(mant_val + 2, NULL);
1159 _shift_left(temp, sc_get_buffer(), NULL);
1164 sc_val_from_ulong(0, NULL);
1167 _save_result(_mant(result));
1169 /* bits from the upper word */
1170 sc_val_from_ulong(mantissa0, temp);
1171 sc_val_from_ulong(34, NULL);
1172 _shift_left(temp, sc_get_buffer(), temp);
1173 sc_or(_mant(result), temp, _mant(result));
1175 /* bits from the lower word */
1176 sc_val_from_ulong(mantissa1, temp);
1177 sc_val_from_ulong(2, NULL);
1178 _shift_left(temp, sc_get_buffer(), temp);
1179 sc_or(_mant(result), temp, _mant(result));
1181 /* _normalize expects the radix point to be normal, so shift mantissa of subnormal
1182 * origin one to the left */
1185 sc_val_from_ulong(1, NULL);
1186 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1189 _normalize(result, result, 0);
1191 TRACEPRINTF(("val_from_float results in %s\n", fc_print(result, temp, calc_buffer_size, FC_PACKED)));
1196 LLDBL fc_val_to_float(const void *val)
1210 #ifdef HAVE_LONG_DOUBLE
1211 char result_exponent = 15;
1212 char result_mantissa = 64;
1214 char result_exponent = 11;
1215 char result_mantissa = 52;
1218 temp = alloca(calc_buffer_size);
1219 #ifdef HAVE_EXPLICIT_ONE
1220 value = fc_cast(val, result_exponent, result_mantissa-1, temp);
1222 value = fc_cast(val, result_exponent, result_mantissa, temp);
1225 sign = _sign(value);
1227 /* @@@ long double exponent is 15bit, so the use of sc_val_to_long should not
1228 * lead to wrong results */
1229 exponent = sc_val_to_long(_exp(value)) ;
1231 sc_val_from_ulong(2, NULL);
1232 _shift_right(_mant(value), sc_get_buffer(), _mant(value));
1237 for (byte_offset = 0; byte_offset < 4; byte_offset++)
1238 mantissa1 |= sc_sub_bits(_mant(value), result_mantissa, byte_offset) << (byte_offset<<3);
1240 for (; (byte_offset<<3) < result_mantissa; byte_offset++)
1241 mantissa0 |= sc_sub_bits(_mant(value), result_mantissa, byte_offset) << ((byte_offset-4)<<3);
1243 #ifdef HAVE_LONG_DOUBLE
1244 buildval.val.high = sign << 15;
1245 buildval.val.high |= exponent;
1246 buildval.val.mid = mantissa0;
1247 buildval.val.low = mantissa1;
1248 #else /* no long double */
1249 mantissa0 &= 0x000FFFFF; /* get rid of garbage */
1250 buildval.val.high = sign << 31;
1251 buildval.val.high |= exponent << 20;
1252 buildval.val.high |= mantissa0;
1253 buildval.val.low = mantissa1;
1256 TRACEPRINTF(("val_to_float: %d-%x-%x%x\n", sign, exponent, mantissa0, mantissa1));
1260 char* fc_cast(const void *val, char exp_size, char mant_size, char *result)
1262 const char *value = (const char*) val;
1264 int exp_offset, val_bias, res_bias;
1266 if (result == NULL) result = calc_buffer;
1267 temp = alloca(value_size);
1269 if (_desc(value).exponent_size == exp_size && _desc(value).mantissa_size == mant_size)
1271 if (value != result) memcpy(result, value, calc_buffer_size);
1275 /* set the descriptor of the new value */
1276 _desc(result).exponent_size = exp_size;
1277 _desc(result).mantissa_size = mant_size;
1278 _desc(result).clss = _desc(value).clss;
1280 _sign(result) = _sign(value);
1282 /* when the mantissa sizes differ normalizing has to shift to align it.
1283 * this would change the exponent, which is unwanted. So calculate this
1284 * offset and add it */
1285 val_bias = (1<<_desc(value).exponent_size)/2-1;
1286 res_bias = (1<<exp_size)/2-1;
1288 exp_offset = (res_bias - val_bias) - (_desc(value).mantissa_size - mant_size);
1289 sc_val_from_long(exp_offset, temp);
1290 sc_add(_exp(value), temp, _exp(result));
1292 /* _normalize expects normalized radix point */
1293 if (_desc(val).clss == SUBNORMAL) {
1294 sc_val_from_ulong(1, NULL);
1295 _shift_left(_mant(val), sc_get_buffer(), _mant(result));
1296 } else if (value != result) {
1297 memcpy(_mant(result), _mant(value), value_size);
1299 memmove(_mant(result), _mant(value), value_size);
1302 _normalize(result, result, 0);
1303 TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1307 char* fc_get_max(unsigned int exponent_size, unsigned int mantissa_size, char* result)
1309 if (result == NULL) result = calc_buffer;
1311 _desc(result).exponent_size = exponent_size;
1312 _desc(result).mantissa_size = mantissa_size;
1313 _desc(result).clss = NORMAL;
1317 sc_val_from_ulong((1<<exponent_size) - 2, _exp(result));
1319 sc_max_from_bits(mantissa_size + 1, 0, _mant(result));
1320 sc_val_from_ulong(2, NULL);
1321 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1326 char* fc_get_min(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1328 if (result == NULL) result = calc_buffer;
1330 fc_get_max(exponent_size, mantissa_size, result);
1336 char* fc_get_snan(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1338 if (result == NULL) result = calc_buffer;
1340 _desc(result).exponent_size = exponent_size;
1341 _desc(result).mantissa_size = mantissa_size;
1342 _desc(result).clss = NAN;
1346 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1348 /* signaling NaN has non-zero mantissa with msb not set */
1349 sc_val_from_ulong(1, _mant(result));
1354 char* fc_get_qnan(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1356 if (result == NULL) result = calc_buffer;
1358 _desc(result).exponent_size = exponent_size;
1359 _desc(result).mantissa_size = mantissa_size;
1360 _desc(result).clss = NAN;
1364 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1366 /* quiet NaN has the msb of the mantissa set, so shift one there */
1367 sc_val_from_ulong(1, _mant(result));
1368 /* mantissa_size >+< 1 because of two extra rounding bits */
1369 sc_val_from_ulong(mantissa_size + 1, NULL);
1370 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1375 char* fc_get_plusinf(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1377 if (result == NULL) result = calc_buffer;
1379 _desc(result).exponent_size = exponent_size;
1380 _desc(result).mantissa_size = mantissa_size;
1381 _desc(result).clss = NORMAL;
1385 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1387 sc_val_from_ulong(0, _mant(result));
1392 char* fc_get_minusinf(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1394 if (result == NULL) result = calc_buffer;
1396 fc_get_plusinf(exponent_size, mantissa_size, result);
1402 int fc_comp(const void *a, const void *b)
1404 const char *val_a = (const char*)a;
1405 const char *val_b = (const char*)b;
1409 * shortcut: if both values are identical, they are either
1410 * Unordered if NaN or equal
1413 return _desc(val_a).clss == NAN ? 2 : 0;
1415 /* unordered if one is a NaN */
1416 if (_desc(val_a).clss == NAN || _desc(val_b).clss == NAN)
1419 /* zero is equal independent of sign */
1420 if ((_desc(val_a).clss == ZERO) && (_desc(val_b).clss == ZERO))
1423 /* different signs make compare easy */
1424 if (_sign(val_a) != _sign(val_b))
1425 return (_sign(val_a)==0)?(1):(-1);
1427 mul = _sign(a) ? -1 : 1;
1429 /* both infinity means equality */
1430 if ((_desc(val_a).clss == INF) && (_desc(val_b).clss == INF))
1433 /* infinity is bigger than the rest */
1434 if (_desc(val_a).clss == INF)
1436 if (_desc(val_b).clss == INF)
1439 /* check first exponent, that mantissa if equal */
1440 switch (sc_comp(_exp(val_a), _exp(val_b))) {
1446 return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1452 int fc_is_zero(const void *a)
1454 return _desc(a).clss == ZERO;
1457 int fc_is_negative(const void *a)
1462 int fc_is_inf(const void *a)
1464 return _desc(a).clss == INF;
1467 int fc_is_nan(const void *a)
1469 return _desc(a).clss == NAN;
1472 int fc_is_subnormal(const void *a)
1474 return _desc(a).clss == SUBNORMAL;
1477 char *fc_print(const void *a, char *buf, int buflen, unsigned base)
1482 val = (const char*)a;
1484 mul_1 = alloca(calc_buffer_size);
1488 switch (_desc(val).clss) {
1490 if (buflen >= 8+_sign(val)) sprintf(buf, "%sINFINITY", _sign(val)?"-":"");
1491 else snprintf(buf, buflen, "%sINF", _sign(val)?"-":NULL);
1494 snprintf(buf, buflen, "NAN");
1497 snprintf(buf, buflen, "0.0");
1500 /* XXX to be implemented */
1501 #ifdef HAVE_LONG_DOUBLE
1502 /* XXX 30 is arbitrary */
1503 snprintf(buf, buflen, "%.30LE", fc_val_to_float(val));
1505 snprintf(buf, buflen, "%.18E", fc_val_to_float(val));
1511 switch (_desc(val).clss) {
1513 if (buflen >= 8+_sign(val)) sprintf(buf, "%sINFINITY", _sign(val)?"-":"");
1514 else snprintf(buf, buflen, "%sINF", _sign(val)?"-":NULL);
1517 snprintf(buf, buflen, "NAN");
1520 snprintf(buf, buflen, "0.0");
1523 #ifdef HAVE_LONG_DOUBLE
1524 snprintf(buf, buflen, "%LA", fc_val_to_float(val));
1526 snprintf(buf, buflen, "%A", fc_val_to_float(val));
1533 snprintf(buf, buflen, "%s", sc_print(_pack(val, mul_1), value_size*4, SC_HEX, 0));
1534 buf[buflen - 1] = '\0';
1540 unsigned char fc_sub_bits(const void *value, unsigned num_bits, unsigned byte_ofs)
1542 /* this is used to cache the packed version of the value */
1543 static char *pack = NULL;
1545 if (pack == NULL) pack = xmalloc(value_size);
1548 _pack((const char*)value, pack);
1550 return sc_sub_bits(pack, num_bits, byte_ofs);
1553 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode)
1555 if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1556 rounding_mode = mode;
1558 return rounding_mode;
1561 fc_rounding_mode_t fc_get_rounding_mode(void)
1563 return rounding_mode;
1566 void init_fltcalc(int precision)
1568 if (calc_buffer == NULL) {
1569 /* does nothing if already init */
1570 if (precision == 0) precision = FC_DEFAULT_PRECISION;
1572 init_strcalc(precision + 4);
1574 /* needs additionally two bits to round, a bit as explicit 1., and one for
1575 * addition overflow */
1576 max_precision = sc_get_precision() - 4;
1577 if (max_precision < precision)
1578 printf("WARING: not enough precision available, using %d\n", max_precision);
1580 rounding_mode = FC_TONEAREST;
1581 value_size = sc_get_buffer_length();
1583 EXPONENT_POS = SIGN_POS + sizeof(char);
1584 MANTISSA_POS = EXPONENT_POS + value_size;
1585 DESCRIPTOR_POS = MANTISSA_POS + value_size;
1586 calc_buffer_size = DESCRIPTOR_POS + sizeof(descriptor_t);
1588 calc_buffer = xmalloc(calc_buffer_size);
1589 memset(calc_buffer, 0, calc_buffer_size);
1590 DEBUGPRINTF(("init fltcalc:\n\tVALUE_SIZE = %d\n\tSIGN_POS = %d\n\tEXPONENT_POS = %d\n\tMANTISSA_POS = %d\n\tDESCRIPTOR_POS = %d\n\tCALC_BUFFER_SIZE = %d\n\tcalc_buffer = %p\n\n", value_size, SIGN_POS, EXPONENT_POS, MANTISSA_POS, DESCRIPTOR_POS, calc_buffer_size, calc_buffer));
1591 #ifdef HAVE_LONG_DOUBLE
1592 DEBUGPRINTF(("\tUsing long double (1-15-64) interface\n"));
1594 DEBUGPRINTF(("\tUsing double (1-11-52) interface\n"));
1596 #ifdef WORDS_BIGENDIAN
1597 DEBUGPRINTF(("\tWord order is big endian\n\n"));
1599 DEBUGPRINTF(("\tWord order is little endian\n\n"));
1604 void finish_fltcalc (void) {
1605 free(calc_buffer); calc_buffer = NULL;
1608 /* definition of interface functions */