2 * Copyright (C) 1995-2008 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
6 * This file may be distributed and/or modified under the terms of the
7 * GNU General Public License version 2 as published by the Free Software
8 * Foundation and appearing in the file LICENSE.GPL included in the
9 * packaging of this file.
11 * Licensees holding valid libFirm Professional Edition licenses may use
12 * this file in accordance with the libFirm Commercial License.
13 * Agreement provided with the Software.
15 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * @brief tarval floating point calculations
24 * @author Mathias Heil
35 #include <math.h> /* need isnan() and isinf() (will be changed)*/
36 /* undef some reused constants defined by math.h */
41 #ifdef HAVE_INTTYPES_H
42 # include <inttypes.h>
55 /** The number of extra precision rounding bits */
56 #define ROUNDING_BITS 2
58 typedef uint32_t UINT32;
60 #ifdef HAVE_LONG_DOUBLE
61 #ifdef WORDS_BIGENDIAN
68 volatile long double d;
77 volatile long double d;
81 #ifdef WORDS_BIGENDIAN
100 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
102 /* our floating point value */
104 ieee_descriptor_t desc;
106 char value[1]; /* exp[value_size] + mant[value_size] */
109 #define _exp(a) &((a)->value[0])
110 #define _mant(a) &((a)->value[value_size])
112 #define _save_result(x) memcpy((x), sc_get_buffer(), value_size)
113 #define _shift_right(x, y, res) sc_shr((x), (y), value_size*4, 0, (res))
114 #define _shift_left(x, y, res) sc_shl((x), (y), value_size*4, 0, (res))
118 # define DEBUGPRINTF(x) printf x
120 # define DEBUGPRINTF(x) ((void)0)
123 #ifdef FLTCALC_TRACE_CALC
124 # define TRACEPRINTF(x) printf x
126 # define TRACEPRINTF(x) ((void)0)
129 /** The immediate precision. */
130 static unsigned immediate_prec = 0;
132 /** A temporal buffer. */
133 static fp_value *calc_buffer = NULL;
135 /** Current rounding mode.*/
136 static fc_rounding_mode_t rounding_mode;
138 static int calc_buffer_size;
139 static int value_size;
140 static int max_precision;
143 static int fc_exact = 1;
146 static void fail_char(const char *str, unsigned int len, int pos) {
148 printf("ERROR: Unexpected character '%c'\n", *(str + pos));
150 printf("ERROR: Unexpected end of string\n");
151 while (len-- && *str) printf("%c", *str++); printf("\n");
152 while (pos--) printf(" "); printf("^\n");
153 /* the front end has to to check constant strings */
158 /** pack machine-like */
159 static void *pack(const fp_value *int_float, void *packed) {
162 fp_value *val_buffer;
165 temp = alloca(value_size);
166 shift_val = alloca(value_size);
168 switch ((value_class_t)int_float->desc.clss) {
170 val_buffer = alloca(calc_buffer_size);
171 fc_get_qnan(&int_float->desc, val_buffer);
172 int_float = val_buffer;
176 val_buffer = alloca(calc_buffer_size);
177 fc_get_plusinf(&int_float->desc, val_buffer);
178 val_buffer->sign = int_float->sign;
179 int_float = val_buffer;
185 assert(int_float->desc.explicit_one <= 1);
187 /* pack sign: move it to the left after exponent AND mantissa */
188 sc_val_from_ulong(int_float->sign, temp);
190 pos = int_float->desc.exponent_size + int_float->desc.mantissa_size + int_float->desc.explicit_one;
191 sc_val_from_ulong(pos, NULL);
192 _shift_left(temp, sc_get_buffer(), packed);
194 /* pack exponent: move it to the left after mantissa */
195 pos = int_float->desc.mantissa_size + int_float->desc.explicit_one;
196 sc_val_from_ulong(pos, shift_val);
197 _shift_left(_exp(int_float), shift_val, temp);
199 /* combine sign|exponent */
200 sc_or(temp, packed, packed);
202 /* extract mantissa */
203 /* remove rounding bits */
204 sc_val_from_ulong(ROUNDING_BITS, shift_val);
205 _shift_right(_mant(int_float), shift_val, temp);
207 /* remove leading 1 (or 0 if denormalized) */
208 sc_max_from_bits(pos, 0, shift_val); /* all mantissa bits are 1's */
209 sc_and(temp, shift_val, temp);
211 /* combine sign|exponent|mantissa */
212 sc_or(temp, packed, packed);
218 * Normalize a fp_value.
220 * @return non-zero if result is exact
222 static int normalize(const fp_value *in_val, fp_value *out_val, int sticky) {
225 char lsb, guard, round, round_dir = 0;
226 char *temp = alloca(value_size);
228 /* save rounding bits at the end */
229 hsb = ROUNDING_BITS + in_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(in_val)) - 1;
231 if (in_val != out_val) {
232 out_val->sign = in_val->sign;
233 memcpy(&out_val->desc, &in_val->desc, sizeof(out_val->desc));
236 out_val->desc.clss = NORMAL;
238 /* mantissa all zeros, so zero exponent (because of explicit one) */
239 if (hsb == ROUNDING_BITS + in_val->desc.mantissa_size) {
240 sc_val_from_ulong(0, _exp(out_val));
244 /* shift the first 1 into the left of the radix point (i.e. hsb == -1) */
247 sc_val_from_ulong(-hsb-1, temp);
249 _shift_right(_mant(in_val), temp, _mant(out_val));
251 /* remember if some bits were shifted away */
252 if (sc_had_carry()) {
256 sc_add(_exp(in_val), temp, _exp(out_val));
257 } else if (hsb > -1) {
259 sc_val_from_ulong(hsb+1, temp);
261 _shift_left(_mant(in_val), temp, _mant(out_val));
263 sc_sub(_exp(in_val), temp, _exp(out_val));
266 /* check for exponent underflow */
267 if (sc_is_negative(_exp(out_val)) || sc_is_zero(_exp(out_val))) {
268 DEBUGPRINTF(("Exponent underflow!\n"));
269 /* exponent underflow */
270 /* shift the mantissa right to have a zero exponent */
271 sc_val_from_ulong(1, temp);
272 sc_sub(temp, _exp(out_val), NULL);
274 _shift_right(_mant(out_val), sc_get_buffer(), _mant(out_val));
275 if (sc_had_carry()) {
279 /* denormalized means exponent of zero */
280 sc_val_from_ulong(0, _exp(out_val));
282 out_val->desc.clss = SUBNORMAL;
285 /* perform rounding by adding a value that clears the guard bit and the round bit
286 * and either causes a carry to round up or not */
287 /* get the last 3 bits of the value */
288 lsb = sc_sub_bits(_mant(out_val), out_val->desc.mantissa_size + ROUNDING_BITS, 0) & 0x7;
289 guard = (lsb&0x2)>>1;
292 switch (rounding_mode) {
294 /* round to nearest representable value, if in doubt choose the version
296 round_dir = guard && (sticky || round || lsb>>2);
299 /* if positive: round to one if the exact value is bigger, else to zero */
300 round_dir = (!out_val->sign && (guard || round || sticky));
303 /* if negative: round to one if the exact value is bigger, else to zero */
304 round_dir = (out_val->sign && (guard || round || sticky));
307 /* always round to 0 (chopping mode) */
311 DEBUGPRINTF(("Rounding (s%d, l%d, g%d, r%d, s%d) %s\n", out_val->sign, lsb>>2, guard, round, sticky, (round_dir)?"up":"down"));
313 if (round_dir == 1) {
314 guard = (round^guard)<<1;
315 lsb = !(round || guard)<<2 | guard | round;
317 lsb = -((guard<<1) | round);
320 /* add the rounded value */
322 sc_val_from_long(lsb, temp);
323 sc_add(_mant(out_val), temp, _mant(out_val));
327 /* could have rounded down to zero */
328 if (sc_is_zero(_mant(out_val)) && (out_val->desc.clss == SUBNORMAL))
329 out_val->desc.clss = ZERO;
331 /* check for rounding overflow */
332 hsb = ROUNDING_BITS + out_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(out_val)) - 1;
333 if ((out_val->desc.clss != SUBNORMAL) && (hsb < -1)) {
334 sc_val_from_ulong(1, temp);
335 _shift_right(_mant(out_val), temp, _mant(out_val));
336 if (exact && sc_had_carry())
338 sc_add(_exp(out_val), temp, _exp(out_val));
339 } else if ((out_val->desc.clss == SUBNORMAL) && (hsb == -1)) {
340 /* overflow caused the mantissa to be normal again,
341 * so adapt the exponent accordingly */
342 sc_val_from_ulong(1, temp);
343 sc_add(_exp(out_val), temp, _exp(out_val));
345 out_val->desc.clss = NORMAL;
347 /* no further rounding is needed, because rounding overflow means
348 * the carry of the original rounding was propagated all the way
349 * up to the bit left of the radix point. This implies the bits
350 * to the right are all zeros (rounding is +1) */
352 /* check for exponent overflow */
353 sc_val_from_ulong((1 << out_val->desc.exponent_size) - 1, temp);
354 if (sc_comp(_exp(out_val), temp) != -1) {
355 DEBUGPRINTF(("Exponent overflow!\n"));
356 /* exponent overflow, reaction depends on rounding method:
358 * mode | sign of value | result
359 *--------------------------------------------------------------
360 * TO_NEAREST | + | +inf
362 *--------------------------------------------------------------
363 * TO_POSITIVE | + | +inf
364 * | - | smallest representable value
365 *--------------------------------------------------------------
366 * TO_NEAGTIVE | + | largest representable value
368 *--------------------------------------------------------------
369 * TO_ZERO | + | largest representable value
370 * | - | smallest representable value
371 *--------------------------------------------------------------*/
372 if (out_val->sign == 0) {
373 /* value is positive */
374 switch (rounding_mode) {
377 out_val->desc.clss = INF;
382 fc_get_max(&out_val->desc, out_val);
385 /* value is negative */
386 switch (rounding_mode) {
389 out_val->desc.clss = INF;
394 fc_get_min(&out_val->desc, out_val);
402 * Operations involving NaN's must return NaN.
403 * They are NOT exact.
405 #define handle_NAN(a, b, result) \
407 if (a->desc.clss == NAN) { \
408 if (a != result) memcpy(result, a, calc_buffer_size); \
412 if (b->desc.clss == NAN) { \
413 if (b != result) memcpy(result, b, calc_buffer_size); \
421 * calculate a + b, where a is the value with the bigger exponent
423 static void _fadd(const fp_value *a, const fp_value *b, fp_value *result) {
432 handle_NAN(a, b, result);
434 /* make sure result has a descriptor */
435 if (result != a && result != b)
436 result->desc = a->desc;
438 /* determine if this is an addition or subtraction */
439 sign = a->sign ^ b->sign;
441 /* produce NaN on inf - inf */
442 if (sign && (a->desc.clss == INF) && (b->desc.clss == INF)) {
444 fc_get_qnan(&a->desc, result);
448 temp = alloca(value_size);
449 exp_diff = alloca(value_size);
451 /* get exponent difference */
452 sc_sub(_exp(a), _exp(b), exp_diff);
454 /* initially set sign to be the sign of a, special treatment of subtraction
455 * when exponents are equal is required though.
456 * Also special care about the sign is needed when the mantissas are equal
458 if (sign && sc_val_to_long(exp_diff) == 0) {
459 switch (sc_comp(_mant(a), _mant(b))) {
461 res_sign = a->sign; /* abs(a) is bigger and a is negative */
464 res_sign = (rounding_mode == FC_TONEGATIVE);
467 res_sign = b->sign; /* abs(b) is bigger and b is negative */
470 /* can't be reached */
477 result->sign = res_sign;
479 /* sign has been taken care of, check for special cases */
480 if (a->desc.clss == ZERO || b->desc.clss == INF) {
482 memcpy(result, b, calc_buffer_size);
483 fc_exact = b->desc.clss == NORMAL;
484 result->sign = res_sign;
487 if (b->desc.clss == ZERO || a->desc.clss == INF) {
489 memcpy(result, a, calc_buffer_size);
490 fc_exact = a->desc.clss == NORMAL;
491 result->sign = res_sign;
495 /* shift the smaller value to the right to align the radix point */
496 /* subnormals have their radix point shifted to the right,
497 * take care of this first */
498 if ((b->desc.clss == SUBNORMAL) && (a->desc.clss != SUBNORMAL)) {
499 sc_val_from_ulong(1, temp);
500 sc_sub(exp_diff, temp, exp_diff);
503 _shift_right(_mant(b), exp_diff, temp);
504 sticky = sc_had_carry();
507 if (sticky && sign) {
508 /* if subtracting a little more than the represented value or adding a little
509 * more than the represented value to a negative value this, in addition to the
510 * still set sticky bit, takes account of the 'little more' */
511 char *temp1 = alloca(calc_buffer_size);
512 sc_val_from_ulong(1, temp1);
513 sc_add(temp, temp1, temp);
517 if (sc_comp(_mant(a), temp) == -1)
518 sc_sub(temp, _mant(a), _mant(result));
520 sc_sub(_mant(a), temp, _mant(result));
522 sc_add(_mant(a), temp, _mant(result));
525 /* _normalize expects a 'normal' radix point, adding two subnormals
526 * results in a subnormal radix point -> shifting before normalizing */
527 if ((a->desc.clss == SUBNORMAL) && (b->desc.clss == SUBNORMAL)) {
528 sc_val_from_ulong(1, NULL);
529 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
532 /* resulting exponent is the bigger one */
533 memmove(_exp(result), _exp(a), value_size);
535 fc_exact &= normalize(result, result, sticky);
541 static void _fmul(const fp_value *a, const fp_value *b, fp_value *result) {
548 handle_NAN(a, b, result);
550 temp = alloca(value_size);
552 if (result != a && result != b)
553 result->desc = a->desc;
555 result->sign = res_sign = a->sign ^ b->sign;
557 /* produce NaN on 0 * inf */
558 if (a->desc.clss == ZERO) {
559 if (b->desc.clss == INF) {
560 fc_get_qnan(&a->desc, result);
564 memcpy(result, a, calc_buffer_size);
565 result->sign = res_sign;
569 if (b->desc.clss == ZERO) {
570 if (a->desc.clss == INF) {
571 fc_get_qnan(&a->desc, result);
575 memcpy(result, b, calc_buffer_size);
576 result->sign = res_sign;
581 if (a->desc.clss == INF) {
584 memcpy(result, a, calc_buffer_size);
585 result->sign = res_sign;
588 if (b->desc.clss == INF) {
591 memcpy(result, b, calc_buffer_size);
592 result->sign = res_sign;
596 /* exp = exp(a) + exp(b) - excess */
597 sc_add(_exp(a), _exp(b), _exp(result));
599 sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 1, temp);
600 sc_sub(_exp(result), temp, _exp(result));
602 /* mixed normal, subnormal values introduce an error of 1, correct it */
603 if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
604 sc_val_from_ulong(1, temp);
605 sc_add(_exp(result), temp, _exp(result));
608 sc_mul(_mant(a), _mant(b), _mant(result));
610 /* realign result: after a multiplication the digits right of the radix
611 * point are the sum of the factors' digits after the radix point. As all
612 * values are normalized they both have the same amount of these digits,
613 * which has to be restored by proper shifting
614 * because of the rounding bits */
615 sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
617 _shift_right(_mant(result), temp, _mant(result));
618 sticky = sc_had_carry();
621 fc_exact &= normalize(result, result, sticky);
627 static void _fdiv(const fp_value *a, const fp_value *b, fp_value *result) {
629 char *temp, *dividend;
634 handle_NAN(a, b, result);
636 temp = alloca(value_size);
637 dividend = alloca(value_size);
639 if (result != a && result != b)
640 result->desc = a->desc;
642 result->sign = res_sign = a->sign ^ b->sign;
644 /* produce NAN on 0/0 and inf/inf */
645 if (a->desc.clss == ZERO) {
646 if (b->desc.clss == ZERO) {
648 fc_get_qnan(&a->desc, result);
653 memcpy(result, a, calc_buffer_size);
654 result->sign = res_sign;
659 if (b->desc.clss == INF) {
661 if (a->desc.clss == INF) {
663 fc_get_qnan(&a->desc, result);
666 sc_val_from_ulong(0, NULL);
667 _save_result(_exp(result));
668 _save_result(_mant(result));
669 result->desc.clss = ZERO;
674 if (a->desc.clss == INF) {
678 memcpy(result, a, calc_buffer_size);
679 result->sign = res_sign;
682 if (b->desc.clss == ZERO) {
684 /* division by zero */
686 fc_get_minusinf(&a->desc, result);
688 fc_get_plusinf(&a->desc, result);
692 /* exp = exp(a) - exp(b) + excess - 1*/
693 sc_sub(_exp(a), _exp(b), _exp(result));
694 sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 2, temp);
695 sc_add(_exp(result), temp, _exp(result));
697 /* mixed normal, subnormal values introduce an error of 1, correct it */
698 if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
699 sc_val_from_ulong(1, temp);
700 sc_add(_exp(result), temp, _exp(result));
703 /* mant(res) = mant(a) / 1/2mant(b) */
704 /* to gain more bits of precision in the result the dividend could be
705 * shifted left, as this operation does not loose bits. This would not
706 * fit into the integer precision, but due to the rounding bits (which
707 * are always zero because the values are all normalized) the divisor
708 * can be shifted right instead to achieve the same result */
709 sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
711 _shift_left(_mant(a), temp, dividend);
714 char *divisor = alloca(calc_buffer_size);
715 sc_val_from_ulong(1, divisor);
716 _shift_right(_mant(b), divisor, divisor);
717 sc_div(dividend, divisor, _mant(result));
718 sticky = sc_had_carry();
722 fc_exact &= normalize(result, result, sticky);
726 static void _power_of_ten(int exp, ieee_descriptor_t *desc, char *result) {
733 /* set new descriptor (else result is supposed to already have one) */
735 result->desc = *desc;
737 build = alloca(value_size);
738 temp = alloca(value_size);
740 sc_val_from_ulong((1 << (result->desc.exponent_size - 1)) - 1, _exp(result));
743 /* temp is value of ten now */
744 sc_val_from_ulong(10, NULL);
747 for (exp--; exp > 0; exp--) {
749 sc_mul(build, temp, NULL);
753 /* temp is amount of left shift needed to put the value left of the radix point */
754 sc_val_from_ulong(result->desc.mantissa_size + ROUNDING_BITS, temp);
756 _shift_left(build, temp, _mant(result));
758 _normalize(result, result, 0);
764 * Truncate the fractional part away.
766 * This does not clip to any integer range.
768 static void _trunc(const fp_value *a, fp_value *result) {
770 * When exponent == 0 all bits left of the radix point
771 * are the integral part of the value. For 15bit exp_size
772 * this would require a left shift of max. 16383 bits which
774 * But it is enough to ensure that no bit right of the radix
775 * point remains set. This restricts the interesting
776 * exponents to the interval [0, mant_size-1].
777 * Outside this interval the truncated value is either 0 or
778 * it does not have fractional parts.
781 int exp_bias, exp_val;
784 /* fixme: can be exact */
787 temp = alloca(value_size);
790 result->desc = a->desc;
792 exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
793 exp_val = sc_val_to_long(_exp(a)) - exp_bias;
796 sc_val_from_ulong(0, NULL);
797 _save_result(_exp(result));
798 _save_result(_mant(result));
799 result->desc.clss = ZERO;
804 if (exp_val > a->desc.mantissa_size) {
806 memcpy(result, a, calc_buffer_size);
811 /* set up a proper mask to delete all bits right of the
812 * radix point if the mantissa had been shifted until exp == 0 */
813 sc_max_from_bits(1 + exp_val, 0, temp);
814 sc_val_from_long(a->desc.mantissa_size - exp_val + 2, NULL);
815 _shift_left(temp, sc_get_buffer(), temp);
817 /* and the mask and return the result */
818 sc_and(_mant(a), temp, _mant(result));
820 if (a != result) memcpy(_exp(result), _exp(a), value_size);
824 * functions defined in fltcalc.h
826 const void *fc_get_buffer(void) {
830 int fc_get_buffer_length(void) {
831 return calc_buffer_size;
834 void *fc_val_from_str(const char *str, unsigned int len, const ieee_descriptor_t *desc, void *result) {
846 int exp_int, hsb, state;
851 char *mant_str, *exp_val, *power_val;
854 if (result == NULL) result = calc_buffer;
856 exp_val = alloca(value_size);
857 power_val = alloca(calc_buffer_size);
858 mant_str = alloca((len)?(len):(strlen(str)));
860 result->desc.exponent_size = desc->exponent_size;
861 result->desc.mantissa_size = desc->mantissa_size;
862 result->desc.explicit_one = desc->explicit_one;
863 result->desc.clss = NORMAL;
870 while (len == 0 || str-old_str < len) {
886 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
893 state = RIGHT_OF_DOT;
904 fail_char(old_str, len, str - old_str);
910 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
911 mant_str[pos++] = *(str++);
915 state = RIGHT_OF_DOT;
926 mant_str[pos] = '\0';
930 fail_char(old_str, len, str - old_str);
936 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
937 mant_str[pos++] = *(str++);
948 mant_str[pos] = '\0';
952 fail_char(old_str, len, str - old_str);
962 if (*(str-1) != 'e' && *(str-1) != 'E') fail_char(old_str, len, str - old_str);
966 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
967 mant_str[pos] = '\0';
974 fail_char(old_str, len, str - old_str);
980 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
985 case '\0': goto done;
988 fail_char(old_str, len, str - old_str);
991 } /* switch(state) */
994 sc_val_from_str(mant_str, strlen(mant_str), _mant(result));
996 /* shift to put value left of radix point */
997 sc_val_from_ulong(mant_size + ROUNDING_BITS, exp_val);
999 _shift_left(_mant(result), exp_val, _mant(result));
1001 sc_val_from_ulong((1 << (exp_size - 1)) - 1, _exp(result));
1003 _normalize(result, result, 0);
1005 if (state == EXPONENT) {
1006 exp_int -= atoi(str-pos);
1009 _power_of_ten(exp_int, &result->desc, power_val);
1011 _fdiv(result, power_val, result);
1015 /* XXX excuse of an implementation to make things work */
1017 fp_value *tmp = alloca(calc_buffer_size);
1018 ieee_descriptor_t tmp_desc;
1021 #ifdef HAVE_LONG_DOUBLE
1022 val = strtold(str, NULL);
1023 DEBUGPRINTF(("val_from_str(%s)\n", str));
1024 tmp_desc.exponent_size = 15;
1025 tmp_desc.mantissa_size = 63;
1026 tmp_desc.explicit_one = 1;
1027 tmp_desc.clss = NORMAL;
1028 fc_val_from_ieee754(val, &tmp_desc, tmp);
1030 val = strtod(str, NULL);
1031 DEBUGPRINTF(("val_from_str(%s)\n", str));
1032 tmp_desc.exponent_size = 11;
1033 tmp_desc.mantissa_size = 52;
1034 tmp_desc.explicit_one = 0;
1035 tmp_desc.clss = NORMAL;
1036 fc_val_from_ieee754(val, &tmp_desc, tmp);
1037 #endif /* HAVE_LONG_DOUBLE */
1038 return fc_cast(tmp, desc, result);
1042 fp_value *fc_val_from_ieee754(LLDBL l, const ieee_descriptor_t *desc, fp_value *result) {
1044 int bias_res, bias_val, mant_val;
1046 UINT32 sign, exponent, mantissa0, mantissa1;
1049 bias_res = ((1 << (desc->exponent_size - 1)) - 1);
1051 #ifdef HAVE_LONG_DOUBLE
1054 sign = (srcval.val.high & 0x00008000) != 0;
1055 exponent = (srcval.val.high & 0x00007FFF) ;
1056 mantissa0 = srcval.val.mid;
1057 mantissa1 = srcval.val.low;
1058 #else /* no long double */
1061 sign = (srcval.val.high & 0x80000000) != 0;
1062 exponent = (srcval.val.high & 0x7FF00000) >> 20;
1063 mantissa0 = srcval.val.high & 0x000FFFFF;
1064 mantissa1 = srcval.val.low;
1067 #ifdef HAVE_LONG_DOUBLE
1068 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)); */
1069 DEBUGPRINTF(("(%d-%.4X-%.8X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1071 TRACEPRINTF(("val_from_float(%.8X%.8X)\n", srcval.val.high, srcval.val.low));
1072 DEBUGPRINTF(("(%d-%.3X-%.5X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1075 if (result == NULL) result = calc_buffer;
1076 temp = alloca(value_size);
1078 /* CLEAR the buffer, else some bits might be uninitialized */
1079 memset(result, 0, fc_get_buffer_length());
1081 result->desc.exponent_size = desc->exponent_size;
1082 result->desc.mantissa_size = desc->mantissa_size;
1083 result->desc.explicit_one = desc->explicit_one;
1086 result->sign = sign;
1088 /* sign and flag suffice to identify NaN or inf, no exponent/mantissa
1089 * encoding is needed. the function can return immediately in these cases */
1091 result->desc.clss = NAN;
1092 TRACEPRINTF(("val_from_float resulted in NAN\n"));
1095 else if (isinf(l)) {
1096 result->desc.clss = INF;
1097 TRACEPRINTF(("val_from_float resulted in %sINF\n", (result->sign == 1) ? "-" : ""));
1101 /* build exponent, because input and output exponent and mantissa sizes may differ
1102 * this looks more complicated than it is: unbiased input exponent + output bias,
1103 * minus the mantissa difference which is added again later when the output float
1104 * becomes normalized */
1105 sc_val_from_long((exponent - bias_val + bias_res) - (mant_val - desc->mantissa_size), _exp(result));
1107 /* build mantissa representation */
1108 if (exponent != 0) {
1109 /* insert the hidden bit */
1110 sc_val_from_ulong(1, temp);
1111 sc_val_from_ulong(mant_val + ROUNDING_BITS, NULL);
1112 _shift_left(temp, sc_get_buffer(), NULL);
1115 sc_val_from_ulong(0, NULL);
1118 _save_result(_mant(result));
1120 /* bits from the upper word */
1121 sc_val_from_ulong(mantissa0, temp);
1122 sc_val_from_ulong(34, NULL);
1123 _shift_left(temp, sc_get_buffer(), temp);
1124 sc_or(_mant(result), temp, _mant(result));
1126 /* bits from the lower word */
1127 sc_val_from_ulong(mantissa1, temp);
1128 sc_val_from_ulong(ROUNDING_BITS, NULL);
1129 _shift_left(temp, sc_get_buffer(), temp);
1130 sc_or(_mant(result), temp, _mant(result));
1132 /* _normalize expects the radix point to be normal, so shift mantissa of subnormal
1133 * origin one to the left */
1134 if (exponent == 0) {
1135 sc_val_from_ulong(1, NULL);
1136 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1139 normalize(result, result, 0);
1141 TRACEPRINTF(("val_from_float results in %s\n", fc_print(result, temp, calc_buffer_size, FC_PACKED)));
1146 LLDBL fc_val_to_ieee754(const fp_value *val) {
1148 fp_value *temp = NULL;
1158 ieee_descriptor_t desc;
1159 unsigned mantissa_size;
1161 #ifdef HAVE_LONG_DOUBLE
1162 desc.exponent_size = 15;
1163 desc.mantissa_size = 63;
1164 desc.explicit_one = 1;
1167 desc.exponent_size = 11;
1168 desc.mantissa_size = 52;
1169 desc.explicit_one = 0;
1172 mantissa_size = desc.mantissa_size + desc.explicit_one;
1174 temp = alloca(calc_buffer_size);
1175 value = fc_cast(val, &desc, temp);
1179 /* @@@ long double exponent is 15bit, so the use of sc_val_to_long should not
1180 * lead to wrong results */
1181 exponent = sc_val_to_long(_exp(value)) ;
1183 sc_val_from_ulong(ROUNDING_BITS, NULL);
1184 _shift_right(_mant(value), sc_get_buffer(), _mant(value));
1189 for (byte_offset = 0; byte_offset < 4; byte_offset++)
1190 mantissa1 |= sc_sub_bits(_mant(value), mantissa_size, byte_offset) << (byte_offset << 3);
1192 for (; (byte_offset<<3) < desc.mantissa_size; byte_offset++)
1193 mantissa0 |= sc_sub_bits(_mant(value), mantissa_size, byte_offset) << ((byte_offset - 4) << 3);
1195 #ifdef HAVE_LONG_DOUBLE
1196 buildval.val.high = sign << 15;
1197 buildval.val.high |= exponent;
1198 buildval.val.mid = mantissa0;
1199 buildval.val.low = mantissa1;
1200 #else /* no long double */
1201 mantissa0 &= 0x000FFFFF; /* get rid of garbage */
1202 buildval.val.high = sign << 31;
1203 buildval.val.high |= exponent << 20;
1204 buildval.val.high |= mantissa0;
1205 buildval.val.low = mantissa1;
1208 TRACEPRINTF(("val_to_float: %d-%x-%x%x\n", sign, exponent, mantissa0, mantissa1));
1212 fp_value *fc_cast(const fp_value *value, const ieee_descriptor_t *desc, fp_value *result) {
1214 int exp_offset, val_bias, res_bias;
1216 if (result == NULL) result = calc_buffer;
1217 temp = alloca(value_size);
1219 if (value->desc.exponent_size == desc->exponent_size &&
1220 value->desc.mantissa_size == desc->mantissa_size &&
1221 value->desc.explicit_one == desc->explicit_one) {
1222 if (value != result)
1223 memcpy(result, value, calc_buffer_size);
1227 if (value->desc.clss == NAN) {
1228 if (sc_get_highest_set_bit(_mant(value)) == value->desc.mantissa_size + 1)
1229 return fc_get_qnan(desc, result);
1231 return fc_get_snan(desc, result);
1234 /* set the descriptor of the new value */
1235 result->desc.exponent_size = desc->exponent_size;
1236 result->desc.mantissa_size = desc->mantissa_size;
1237 result->desc.explicit_one = desc->explicit_one;
1238 result->desc.clss = value->desc.clss;
1240 result->sign = value->sign;
1242 /* when the mantissa sizes differ normalizing has to shift to align it.
1243 * this would change the exponent, which is unwanted. So calculate this
1244 * offset and add it */
1245 val_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1246 res_bias = (1 << (desc->exponent_size - 1)) - 1;
1248 exp_offset = (res_bias - val_bias) - (value->desc.mantissa_size - desc->mantissa_size);
1249 sc_val_from_long(exp_offset, temp);
1250 sc_add(_exp(value), temp, _exp(result));
1252 /* _normalize expects normalized radix point */
1253 if (value->desc.clss == SUBNORMAL) {
1254 sc_val_from_ulong(1, NULL);
1255 _shift_left(_mant(value), sc_get_buffer(), _mant(result));
1256 } else if (value != result) {
1257 memcpy(_mant(result), _mant(value), value_size);
1259 memmove(_mant(result), _mant(value), value_size);
1262 normalize(result, result, 0);
1263 TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1267 fp_value *fc_get_max(const ieee_descriptor_t *desc, fp_value *result) {
1268 if (result == NULL) result = calc_buffer;
1270 result->desc.exponent_size = desc->exponent_size;
1271 result->desc.mantissa_size = desc->mantissa_size;
1272 result->desc.explicit_one = desc->explicit_one;
1273 result->desc.clss = NORMAL;
1277 sc_val_from_ulong((1 << desc->exponent_size) - 2, _exp(result));
1279 sc_max_from_bits(desc->mantissa_size + 1, 0, _mant(result));
1280 sc_val_from_ulong(ROUNDING_BITS, NULL);
1281 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1286 fp_value *fc_get_min(const ieee_descriptor_t *desc, fp_value *result) {
1287 if (result == NULL) result = calc_buffer;
1289 fc_get_max(desc, result);
1295 fp_value *fc_get_snan(const ieee_descriptor_t *desc, fp_value *result) {
1296 if (result == NULL) result = calc_buffer;
1298 result->desc.exponent_size = desc->exponent_size;
1299 result->desc.mantissa_size = desc->mantissa_size;
1300 result->desc.explicit_one = desc->explicit_one;
1301 result->desc.clss = NAN;
1305 sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1307 /* signaling NaN has non-zero mantissa with msb not set */
1308 sc_val_from_ulong(1, _mant(result));
1313 fp_value *fc_get_qnan(const ieee_descriptor_t *desc, fp_value *result) {
1314 if (result == NULL) result = calc_buffer;
1316 result->desc.exponent_size = desc->exponent_size;
1317 result->desc.mantissa_size = desc->mantissa_size;
1318 result->desc.explicit_one = desc->explicit_one;
1319 result->desc.clss = NAN;
1323 sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1325 /* quiet NaN has the msb of the mantissa set, so shift one there */
1326 sc_val_from_ulong(1, _mant(result));
1327 /* mantissa_size >+< 1 because of two extra rounding bits */
1328 sc_val_from_ulong(desc->mantissa_size + 1, NULL);
1329 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1334 fp_value *fc_get_plusinf(const ieee_descriptor_t *desc, fp_value *result) {
1335 if (result == NULL) result = calc_buffer;
1337 result->desc.exponent_size = desc->exponent_size;
1338 result->desc.mantissa_size = desc->mantissa_size;
1339 result->desc.explicit_one = desc->explicit_one;
1340 result->desc.clss = INF;
1344 sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1346 sc_val_from_ulong(0, _mant(result));
1351 fp_value *fc_get_minusinf(const ieee_descriptor_t *desc, fp_value *result) {
1352 if (result == NULL) result = calc_buffer;
1354 fc_get_plusinf(desc, result);
1360 int fc_comp(const fp_value *val_a, const fp_value *val_b) {
1364 * shortcut: if both values are identical, they are either
1365 * Unordered if NaN or equal
1368 return val_a->desc.clss == NAN ? 2 : 0;
1370 /* unordered if one is a NaN */
1371 if (val_a->desc.clss == NAN || val_b->desc.clss == NAN)
1374 /* zero is equal independent of sign */
1375 if ((val_a->desc.clss == ZERO) && (val_b->desc.clss == ZERO))
1378 /* different signs make compare easy */
1379 if (val_a->sign != val_b->sign)
1380 return (val_a->sign == 0) ? (1) : (-1);
1382 mul = val_a->sign ? -1 : 1;
1384 /* both infinity means equality */
1385 if ((val_a->desc.clss == INF) && (val_b->desc.clss == INF))
1388 /* infinity is bigger than the rest */
1389 if (val_a->desc.clss == INF)
1391 if (val_b->desc.clss == INF)
1394 /* check first exponent, that mantissa if equal */
1395 switch (sc_comp(_exp(val_a), _exp(val_b))) {
1401 return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1407 int fc_is_zero(const fp_value *a) {
1408 return a->desc.clss == ZERO;
1411 int fc_is_negative(const fp_value *a) {
1415 int fc_is_inf(const fp_value *a) {
1416 return a->desc.clss == INF;
1419 int fc_is_nan(const fp_value *a) {
1420 return a->desc.clss == NAN;
1423 int fc_is_subnormal(const fp_value *a) {
1424 return a->desc.clss == SUBNORMAL;
1427 char *fc_print(const fp_value *val, char *buf, int buflen, unsigned base) {
1431 mul_1 = alloca(calc_buffer_size);
1435 switch ((value_class_t)val->desc.clss) {
1437 snprintf(buf, buflen, "%cINF", val->sign ? '-' : '+');
1440 snprintf(buf, buflen, "NaN");
1443 snprintf(buf, buflen, "0.0");
1446 flt_val = fc_val_to_ieee754(val);
1447 #ifdef HAVE_LONG_DOUBLE
1448 /* XXX 30 is arbitrary */
1449 snprintf(buf, buflen, "%.30LE", flt_val);
1451 snprintf(buf, buflen, "%.18E", flt_val);
1457 switch ((value_class_t)val->desc.clss) {
1459 snprintf(buf, buflen, "%cINF", val->sign ? '-' : '+');
1462 snprintf(buf, buflen, "NAN");
1465 snprintf(buf, buflen, "0.0");
1468 flt_val = fc_val_to_ieee754(val);
1469 #ifdef HAVE_LONG_DOUBLE
1470 snprintf(buf, buflen, "%LA", flt_val);
1472 snprintf(buf, buflen, "%A", flt_val);
1479 snprintf(buf, buflen, "%s", sc_print(pack(val, mul_1), value_size*4, SC_HEX, 0));
1480 buf[buflen - 1] = '\0';
1486 unsigned char fc_sub_bits(const fp_value *value, unsigned num_bits, unsigned byte_ofs) {
1487 /* this is used to cache the packed version of the value */
1488 static char *packed_value = NULL;
1490 if (packed_value == NULL) packed_value = XMALLOCN(char, value_size);
1493 pack(value, packed_value);
1495 return sc_sub_bits(packed_value, num_bits, byte_ofs);
1498 /* Returns non-zero if the mantissa is zero, i.e. 1.0Exxx */
1499 int fc_zero_mantissa(const fp_value *value) {
1500 return sc_get_lowest_set_bit(_mant(value)) == ROUNDING_BITS + value->desc.mantissa_size;
1503 /* Returns the exponent of a value. */
1504 int fc_get_exponent(const fp_value *value) {
1505 int exp_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1506 return sc_val_to_long(_exp(value)) - exp_bias;
1509 /* Return non-zero if a given value can be converted lossless into another precision */
1510 int fc_can_lossless_conv_to(const fp_value *value, const ieee_descriptor_t *desc) {
1514 /* handle some special cases first */
1515 switch (value->desc.clss) {
1524 /* check if the exponent can be encoded: note, 0 and all ones are reserved for the exponent */
1525 exp_bias = (1 << (desc->exponent_size - 1)) - 1;
1526 v = fc_get_exponent(value) + exp_bias;
1527 if (0 < v && v < (1 << desc->exponent_size) - 1) {
1528 /* exponent can be encoded, now check the mantissa */
1529 v = value->desc.mantissa_size + ROUNDING_BITS - sc_get_lowest_set_bit(_mant(value));
1530 return v < desc->mantissa_size;
1536 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode) {
1537 if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1538 rounding_mode = mode;
1540 return rounding_mode;
1543 fc_rounding_mode_t fc_get_rounding_mode(void) {
1544 return rounding_mode;
1547 void init_fltcalc(int precision) {
1548 if (calc_buffer == NULL) {
1549 /* does nothing if already init */
1550 if (precision == 0) precision = FC_DEFAULT_PRECISION;
1552 init_strcalc(precision + 2 + ROUNDING_BITS);
1554 /* needs additionally rounding bits, one bit as explicit 1., and one for
1555 * addition overflow */
1556 max_precision = sc_get_precision() - (2 + ROUNDING_BITS);
1557 if (max_precision < precision)
1558 printf("WARNING: not enough precision available, using %d\n", max_precision);
1560 rounding_mode = FC_TONEAREST;
1561 value_size = sc_get_buffer_length();
1562 calc_buffer_size = sizeof(fp_value) + 2*value_size - 1;
1564 calc_buffer = xmalloc(calc_buffer_size);
1565 memset(calc_buffer, 0, calc_buffer_size);
1566 DEBUGPRINTF(("init fltcalc:\n\tVALUE_SIZE = %d\ntCALC_BUFFER_SIZE = %d\n\tcalc_buffer = %p\n\n", value_size, calc_buffer_size, calc_buffer));
1567 #ifdef HAVE_LONG_DOUBLE
1568 DEBUGPRINTF(("\tUsing long double (1-15-64) interface\n"));
1570 DEBUGPRINTF(("\tUsing double (1-11-52) interface\n"));
1572 #ifdef WORDS_BIGENDIAN
1573 DEBUGPRINTF(("\tWord order is big endian\n\n"));
1575 DEBUGPRINTF(("\tWord order is little endian\n\n"));
1580 void finish_fltcalc (void) {
1581 free(calc_buffer); calc_buffer = NULL;
1584 #ifdef FLTCALC_TRACE_CALC
1585 static char buffer[100];
1588 /* definition of interface functions */
1589 fp_value *fc_add(const fp_value *a, const fp_value *b, fp_value *result) {
1590 if (result == NULL) result = calc_buffer;
1592 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1593 TRACEPRINTF(("+ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1595 /* make the value with the bigger exponent the first one */
1596 if (sc_comp(_exp(a), _exp(b)) == -1)
1597 _fadd(b, a, result);
1599 _fadd(a, b, result);
1601 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1605 fp_value *fc_sub(const fp_value *a, const fp_value *b, fp_value *result) {
1608 if (result == NULL) result = calc_buffer;
1610 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1611 TRACEPRINTF(("- %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1613 temp = alloca(calc_buffer_size);
1614 memcpy(temp, b, calc_buffer_size);
1615 temp->sign = !b->sign;
1616 if (sc_comp(_exp(a), _exp(temp)) == -1)
1617 _fadd(temp, a, result);
1619 _fadd(a, temp, result);
1621 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1625 fp_value *fc_mul(const fp_value *a, const fp_value *b, fp_value *result) {
1626 if (result == NULL) result = calc_buffer;
1628 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1629 TRACEPRINTF(("* %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1631 _fmul(a, b, result);
1633 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1637 fp_value *fc_div(const fp_value *a, const fp_value *b, fp_value *result) {
1638 if (result == NULL) result = calc_buffer;
1640 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1641 TRACEPRINTF(("/ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1643 _fdiv(a, b, result);
1645 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1649 fp_value *fc_neg(const fp_value *a, fp_value *result) {
1650 if (result == NULL) result = calc_buffer;
1652 TRACEPRINTF(("- %s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1655 memcpy(result, a, calc_buffer_size);
1656 result->sign = !a->sign;
1658 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1662 fp_value *fc_int(const fp_value *a, fp_value *result) {
1663 if (result == NULL) result = calc_buffer;
1665 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1666 TRACEPRINTF(("truncated to integer "));
1670 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1674 fp_value *fc_rnd(const fp_value *a, fp_value *result) {
1675 if (result == NULL) result = calc_buffer;
1678 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1679 TRACEPRINTF(("rounded to integer "));
1681 assert(!"fc_rnd() not yet implemented");
1683 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1688 * convert a floating point value into an sc value ...
1690 int fc_flt2int(const fp_value *a, void *result, ir_mode *dst_mode) {
1691 if (a->desc.clss == NORMAL) {
1692 int exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
1693 int exp_val = sc_val_to_long(_exp(a)) - exp_bias;
1696 if (a->sign && !mode_is_signed(dst_mode)) {
1697 /* FIXME: for now we cannot convert this */
1701 assert(exp_val >= 0 && "floating point value not integral before fc_flt2int() call");
1702 shift = exp_val - (a->desc.mantissa_size + ROUNDING_BITS);
1705 sc_shlI(_mant(a), shift, 64, 0, result);
1707 sc_shrI(_mant(a), -shift, 64, 0, result);
1710 /* check for overflow */
1711 highest = sc_get_highest_set_bit(result);
1713 if (mode_is_signed(dst_mode)) {
1714 if (highest == sc_get_lowest_set_bit(result)) {
1715 /* need extra test for MIN_INT */
1716 if (highest >= (int) get_mode_size_bits(dst_mode)) {
1717 /* FIXME: handle overflow */
1721 if (highest >= (int) get_mode_size_bits(dst_mode) - 1) {
1722 /* FIXME: handle overflow */
1727 if (highest >= (int) get_mode_size_bits(dst_mode)) {
1728 /* FIXME: handle overflow */
1734 sc_neg(result, result);
1738 else if (a->desc.clss == ZERO) {
1746 unsigned fc_set_immediate_precision(unsigned bits) {
1747 unsigned old = immediate_prec;
1749 immediate_prec = bits;
1753 int fc_is_exact(void) {