832a7677ba840341568f4a51c6362fc9f1355c2a
[libfirm] / ir / tv / fltcalc.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
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.
10  *
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.
14  *
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
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief    tarval floating point calculations
23  * @date     2003
24  * @author   Mathias Heil
25  * @version  $Id$
26  */
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include "fltcalc.h"
33 #include "strcalc.h"
34
35 #include <math.h>    /* need isnan() and isinf() (will be changed)*/
36 /* undef some reused constants defined by math.h */
37 #ifdef NAN
38 #  undef NAN
39 #endif
40
41 #ifdef HAVE_INTTYPES_H
42 # include <inttypes.h>
43 #endif
44 #ifdef HAVE_STRING_H
45 # include <string.h>
46 #endif
47 #ifdef HAVE_STDLIB_H
48 # include <stdlib.h>
49 #endif
50 #include <stdio.h>
51 #include <assert.h>
52
53 #include "xmalloc.h"
54
55 /** The number of extra precesion rounding bits */
56 #define ROUNDING_BITS 2
57
58 typedef uint32_t UINT32;
59
60 #ifdef HAVE_LONG_DOUBLE
61 #ifdef WORDS_BIGENDIAN
62 typedef union {
63         struct {
64                 UINT32 high;
65                 UINT32 mid;
66                 UINT32 low;
67         } val;
68         volatile long double d;
69 } value_t;
70 #else
71 typedef union {
72         struct {
73                 UINT32 low;
74                 UINT32 mid;
75                 UINT32 high;
76         } val;
77         volatile long double d;
78 } value_t;
79 #endif
80 #else
81 #ifdef WORDS_BIGENDIAN
82 typedef union {
83         struct {
84                 UINT32 high;
85                 UINT32 low;
86         } val;
87         volatile double d;
88 } value_t;
89 #else
90 typedef union {
91         struct {
92                 UINT32 low;
93                 UINT32 high;
94         } val;
95         volatile double d;
96 } value_t;
97 #endif
98 #endif
99
100 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
101
102 /* our floating point value */
103 struct _fp_value {
104         ieee_descriptor_t desc;
105         char sign;
106         char value[1];                  /* exp[value_size] + mant[value_size] */
107 };
108
109 #define _exp(a)  &((a)->value[0])
110 #define _mant(a) &((a)->value[value_size])
111
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))
115
116
117 #ifdef FLTCALC_DEBUG
118 #  define DEBUGPRINTF(x) printf x
119 #else
120 #  define DEBUGPRINTF(x) ((void)0)
121 #endif
122
123 #ifdef FLTCALC_TRACE_CALC
124 #  define TRACEPRINTF(x) printf x
125 #else
126 #  define TRACEPRINTF(x) ((void)0)
127 #endif
128
129 /** The immediate precision. */
130 static unsigned immediate_prec = 0;
131
132 /** A temporal buffer. */
133 static fp_value *calc_buffer = NULL;
134
135 /** Current rounding mode.*/
136 static fc_rounding_mode_t rounding_mode;
137
138 static int calc_buffer_size;
139 static int value_size;
140 static int max_precision;
141
142 /** Exact flag. */
143 static int fc_exact = 1;
144
145 #if 0
146 static void fail_char(const char *str, unsigned int len, int pos) {
147         if (*(str+pos))
148                 printf("ERROR: Unexpected character '%c'\n", *(str + pos));
149         else
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 */
154         exit(-1);
155 }
156 #endif
157
158 /** pack machine-like */
159 static void *pack(const fp_value *int_float, void *packed) {
160         char     *shift_val;
161         char     *temp;
162         fp_value *val_buffer;
163         int      pos;
164
165         temp      = alloca(value_size);
166         shift_val = alloca(value_size);
167
168         switch ((value_class_t)int_float->desc.clss) {
169         case NAN:
170                 val_buffer = alloca(calc_buffer_size);
171                 fc_get_qnan(&int_float->desc, val_buffer);
172                 int_float = val_buffer;
173                 break;
174
175         case INF:
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;
180                 break;
181
182         default:
183                 break;
184         }
185         /* pack sign: move it to the left after exponent AND mantissa */
186         sc_val_from_ulong(int_float->sign, temp);
187
188         pos = int_float->desc.exponent_size + int_float->desc.mantissa_size + int_float->desc.explicit_one;
189         sc_val_from_ulong(pos, NULL);
190         _shift_left(temp, sc_get_buffer(), packed);
191
192         /* pack exponent: move it to the left after mantissa */
193         pos = int_float->desc.mantissa_size + int_float->desc.explicit_one;
194         sc_val_from_ulong(pos, shift_val);
195         _shift_left(_exp(int_float), shift_val, temp);
196
197         /* combine sign|exponent */
198         sc_or(temp, packed, packed);
199
200         /* extract mantissa */
201         /* remove rounding bits */
202         sc_val_from_ulong(ROUNDING_BITS, shift_val);
203         _shift_right(_mant(int_float), shift_val, temp);
204
205         /* remove leading 1 (or 0 if denormalized) */
206         sc_max_from_bits(pos, 0, shift_val); /* all mantissa bits are 1's */
207         sc_and(temp, shift_val, temp);
208
209         /* combine sign|exponent|mantissa */
210         sc_or(temp, packed, packed);
211
212         return packed;
213 }
214
215 /**
216  * Normalize a fp_value.
217  *
218  * @return non-zero if result is exact
219  */
220 static int normalize(const fp_value *in_val, fp_value *out_val, int sticky) {
221         int exact = 1;
222         int hsb;
223         char lsb, guard, round, round_dir = 0;
224         char *temp = alloca(value_size);
225
226         /* save rounding bits at the end */
227         hsb = ROUNDING_BITS + in_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(in_val)) - 1;
228
229         if (in_val != out_val)   {
230                 out_val->sign = in_val->sign;
231                 memcpy(&out_val->desc, &in_val->desc, sizeof(out_val->desc));
232         }
233
234         out_val->desc.clss = NORMAL;
235
236         /* mantissa all zeros, so zero exponent (because of explicit one) */
237         if (hsb == ROUNDING_BITS + in_val->desc.mantissa_size)   {
238                 sc_val_from_ulong(0, _exp(out_val));
239                 hsb = -1;
240         }
241
242         /* shift the first 1 into the left of the radix point (i.e. hsb == -1) */
243         if (hsb < -1)   {
244                 /* shift right */
245                 sc_val_from_ulong(-hsb-1, temp);
246
247                 _shift_right(_mant(in_val), temp, _mant(out_val));
248
249                 /* remember if some bits were shifted away */
250                 if (sc_had_carry()) {
251                         exact = 0;
252                         sticky = 1;
253                 }
254                 sc_add(_exp(in_val), temp, _exp(out_val));
255         } else if (hsb > -1) {
256                 /* shift left */
257                 sc_val_from_ulong(hsb+1, temp);
258
259                 _shift_left(_mant(in_val), temp, _mant(out_val));
260
261                 sc_sub(_exp(in_val), temp, _exp(out_val));
262         }
263
264         /* check for exponent underflow */
265         if (sc_is_negative(_exp(out_val)) || sc_is_zero(_exp(out_val))) {
266                 DEBUGPRINTF(("Exponent underflow!\n"));
267                 /* exponent underflow */
268                 /* shift the mantissa right to have a zero exponent */
269                 sc_val_from_ulong(1, temp);
270                 sc_sub(temp, _exp(out_val), NULL);
271
272                 _shift_right(_mant(out_val), sc_get_buffer(), _mant(out_val));
273                 if (sc_had_carry()) {
274                         exact  = 0;
275                         sticky = 1;
276                 }
277                 /* denormalized means exponent of zero */
278                 sc_val_from_ulong(0, _exp(out_val));
279
280                 out_val->desc.clss = SUBNORMAL;
281         }
282
283         /* perform rounding by adding a value that clears the guard bit and the round bit
284          * and either causes a carry to round up or not */
285         /* get the last 3 bits of the value */
286         lsb = sc_sub_bits(_mant(out_val), out_val->desc.mantissa_size + ROUNDING_BITS, 0) & 0x7;
287         guard = (lsb&0x2)>>1;
288         round = lsb&0x1;
289
290         switch (rounding_mode) {
291         case FC_TONEAREST:
292                 /* round to nearest representable value, if in doubt choose the version
293                  * with lsb == 0 */
294                 round_dir = guard && (sticky || round || lsb>>2);
295                 break;
296         case FC_TOPOSITIVE:
297                 /* if positive: round to one if the exact value is bigger, else to zero */
298                 round_dir = (!out_val->sign && (guard || round || sticky));
299                 break;
300         case FC_TONEGATIVE:
301                 /* if negative: round to one if the exact value is bigger, else to zero */
302                 round_dir = (out_val->sign && (guard || round || sticky));
303                 break;
304         case FC_TOZERO:
305                 /* always round to 0 (chopping mode) */
306                 round_dir = 0;
307                 break;
308         }
309         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"));
310
311         if (round_dir == 1) {
312                 guard = (round^guard)<<1;
313                 lsb = !(round || guard)<<2 | guard | round;
314         } else {
315                 lsb = -((guard<<1) | round);
316         }
317
318         /* add the rounded value */
319         if (lsb != 0) {
320                 sc_val_from_long(lsb, temp);
321                 sc_add(_mant(out_val), temp, _mant(out_val));
322                 exact = 0;
323         }
324
325         /* could have rounded down to zero */
326         if (sc_is_zero(_mant(out_val)) && (out_val->desc.clss == SUBNORMAL))
327                 out_val->desc.clss = ZERO;
328
329         /* check for rounding overflow */
330         hsb = ROUNDING_BITS + out_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(out_val)) - 1;
331         if ((out_val->desc.clss != SUBNORMAL) && (hsb < -1)) {
332                 sc_val_from_ulong(1, temp);
333                 _shift_right(_mant(out_val), temp, _mant(out_val));
334                 if (exact && sc_had_carry())
335                         exact = 0;
336                 sc_add(_exp(out_val), temp, _exp(out_val));
337         } else if ((out_val->desc.clss == SUBNORMAL) && (hsb == -1)) {
338                 /* overflow caused the mantissa to be normal again,
339                  * so adapt the exponent accordingly */
340                 sc_val_from_ulong(1, temp);
341                 sc_add(_exp(out_val), temp, _exp(out_val));
342
343                 out_val->desc.clss = NORMAL;
344         }
345         /* no further rounding is needed, because rounding overflow means
346          * the carry of the original rounding was propagated all the way
347          * up to the bit left of the radix point. This implies the bits
348          * to the right are all zeros (rounding is +1) */
349
350         /* check for exponent overflow */
351         sc_val_from_ulong((1 << out_val->desc.exponent_size) - 1, temp);
352         if (sc_comp(_exp(out_val), temp) != -1) {
353                 DEBUGPRINTF(("Exponent overflow!\n"));
354                 /* exponent overflow, reaction depends on rounding method:
355                  *
356                  * mode        | sign of value |  result
357                  *--------------------------------------------------------------
358                  * TO_NEAREST  |      +        |   +inf
359                  *             |      -        |   -inf
360                  *--------------------------------------------------------------
361                  * TO_POSITIVE |      +        |   +inf
362                  *             |      -        |   smallest representable value
363                  *--------------------------------------------------------------
364                  * TO_NEAGTIVE |      +        |   largest representable value
365                  *             |      -        |   -inf
366                  *--------------------------------------------------------------
367                  * TO_ZERO     |      +        |   largest representable value
368                  *             |      -        |   smallest representable value
369                  *--------------------------------------------------------------*/
370                 if (out_val->sign == 0) {
371                         /* value is positive */
372                         switch (rounding_mode) {
373                         case FC_TONEAREST:
374                         case FC_TOPOSITIVE:
375                                 out_val->desc.clss = INF;
376                                 break;
377
378                         case FC_TONEGATIVE:
379                         case FC_TOZERO:
380                                 fc_get_max(&out_val->desc, out_val);
381                         }
382                 } else {
383                         /* value is negative */
384                         switch (rounding_mode) {
385                         case FC_TONEAREST:
386                         case FC_TONEGATIVE:
387                                 out_val->desc.clss = INF;
388                                 break;
389
390                         case FC_TOPOSITIVE:
391                         case FC_TOZERO:
392                                 fc_get_min(&out_val->desc, out_val);
393                         }
394                 }
395         }
396         return exact;
397 }
398
399 /**
400  * Operations involving NaN's must return NaN
401  */
402 #define handle_NAN(a, b, result) \
403 do {                                                      \
404   if (a->desc.clss == NAN) {                              \
405     if (a != result) memcpy(result, a, calc_buffer_size); \
406     return;                                               \
407   }                                                       \
408   if (b->desc.clss == NAN) {                              \
409     if (b != result) memcpy(result, b, calc_buffer_size); \
410     return;                                               \
411   }                                                       \
412 }while (0)
413
414
415 /**
416  * calculate a + b, where a is the value with the bigger exponent
417  */
418 static void _fadd(const fp_value *a, const fp_value *b, fp_value *result) {
419         char *temp;
420         char *exp_diff;
421
422         char sign, res_sign;
423         char sticky;
424
425         fc_exact = 1;
426
427         handle_NAN(a, b, result);
428
429         /* make sure result has a descriptor */
430         if (result != a && result != b)
431                 result->desc = a->desc;
432
433         /* determine if this is an addition or subtraction */
434         sign = a->sign ^ b->sign;
435
436         /* produce NaN on inf - inf */
437         if (sign && (a->desc.clss == INF) && (b->desc.clss == INF)) {
438                 fc_get_qnan(&a->desc, result);
439                 return;
440         }
441
442         temp     = alloca(value_size);
443         exp_diff = alloca(value_size);
444
445         /* get exponent difference */
446         sc_sub(_exp(a), _exp(b), exp_diff);
447
448         /* initially set sign to be the sign of a, special treatment of subtraction
449          * when exponents are equal is required though.
450          * Also special care about the sign is needed when the mantissas are equal
451          * (+/- 0 ?) */
452         if (sign && sc_val_to_long(exp_diff) == 0) {
453                 switch (sc_comp(_mant(a), _mant(b))) {
454                 case 1:  /* a > b */
455                         res_sign = a->sign;  /* abs(a) is bigger and a is negative */
456                         break;
457                 case 0:  /* a == b */
458                         res_sign = (rounding_mode == FC_TONEGATIVE);
459                         break;
460                 case -1: /* a < b */
461                         res_sign = b->sign; /* abs(b) is bigger and b is negative */
462                         break;
463                 default:
464                         /* can't be reached */
465                         res_sign = 0;
466                         break;
467                 }
468         }
469         else
470                 res_sign = a->sign;
471         result->sign = res_sign;
472
473         /* sign has been taken care of, check for special cases */
474         if (a->desc.clss == ZERO || b->desc.clss == INF) {
475                 if (b != result)
476                         memcpy(result, b, calc_buffer_size);
477                 result->sign = res_sign;
478                 return;
479         }
480         if (b->desc.clss == ZERO || a->desc.clss == INF) {
481                 if (a != result)
482                         memcpy(result, a, calc_buffer_size);
483                 result->sign = res_sign;
484                 return;
485         }
486
487         /* shift the smaller value to the right to align the radix point */
488         /* subnormals have their radix point shifted to the right,
489          * take care of this first */
490         if ((b->desc.clss == SUBNORMAL) && (a->desc.clss != SUBNORMAL)) {
491                 sc_val_from_ulong(1, temp);
492                 sc_sub(exp_diff, temp, exp_diff);
493         }
494
495         _shift_right(_mant(b), exp_diff, temp);
496         sticky = sc_had_carry();
497         fc_exact &= !sticky;
498
499         if (sticky && sign) {
500                 /* if subtracting a little more than the represented value or adding a little
501                  * more than the represented value to a negative value this, in addition to the
502                  * still set sticky bit, takes account of the 'little more' */
503                 char *temp1 = alloca(calc_buffer_size);
504                 sc_val_from_ulong(1, temp1);
505                 sc_add(temp, temp1, temp);
506         }
507
508         if (sign) {
509                 if (sc_comp(_mant(a), temp) == -1)
510                         sc_sub(temp, _mant(a), _mant(result));
511                 else
512                         sc_sub(_mant(a), temp, _mant(result));
513         } else {
514                 sc_add(_mant(a), temp, _mant(result));
515         }
516
517         /* _normalize expects a 'normal' radix point, adding two subnormals
518          * results in a subnormal radix point -> shifting before normalizing */
519         if ((a->desc.clss == SUBNORMAL) && (b->desc.clss == SUBNORMAL)) {
520                 sc_val_from_ulong(1, NULL);
521                 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
522         }
523
524         /* resulting exponent is the bigger one */
525         memmove(_exp(result), _exp(a), value_size);
526
527         fc_exact &= normalize(result, result, sticky);
528 }
529
530 /**
531  * calculate a * b
532  */
533 static void _fmul(const fp_value *a, const fp_value *b, fp_value *result) {
534         int sticky;
535         char *temp;
536         char res_sign;
537
538         fc_exact = 1;
539
540         handle_NAN(a, b, result);
541
542         temp = alloca(value_size);
543
544         if (result != a && result != b)
545                 result->desc = a->desc;
546
547         result->sign = res_sign = a->sign ^ b->sign;
548
549         /* produce NaN on 0 * inf */
550         if (a->desc.clss == ZERO) {
551                 if (b->desc.clss == INF)
552                         fc_get_qnan(&a->desc, result);
553                 else {
554                         if (a != result)
555                                 memcpy(result, a, calc_buffer_size);
556                         result->sign = res_sign;
557                 }
558                 return;
559         }
560         if (b->desc.clss == ZERO) {
561                 if (a->desc.clss == INF)
562                         fc_get_qnan(&a->desc, result);
563                 else {
564                         if (b != result)
565                                 memcpy(result, b, calc_buffer_size);
566                         result->sign = res_sign;
567                 }
568                 return;
569         }
570
571         if (a->desc.clss == INF) {
572                 if (a != result)
573                         memcpy(result, a, calc_buffer_size);
574                 result->sign = res_sign;
575                 return;
576         }
577         if (b->desc.clss == INF) {
578                 if (b != result)
579                         memcpy(result, b, calc_buffer_size);
580                 result->sign = res_sign;
581                 return;
582         }
583
584         /* exp = exp(a) + exp(b) - excess */
585         sc_add(_exp(a), _exp(b), _exp(result));
586
587         sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 1, temp);
588         sc_sub(_exp(result), temp, _exp(result));
589
590         /* mixed normal, subnormal values introduce an error of 1, correct it */
591         if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
592                 sc_val_from_ulong(1, temp);
593                 sc_add(_exp(result), temp, _exp(result));
594         }
595
596         sc_mul(_mant(a), _mant(b), _mant(result));
597
598         /* realign result: after a multiplication the digits right of the radix
599          * point are the sum of the factors' digits after the radix point. As all
600          * values are normalized they both have the same amount of these digits,
601          * which has to be restored by proper shifting
602          * because of the rounding bits */
603         sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
604
605         _shift_right(_mant(result), temp, _mant(result));
606         sticky = sc_had_carry();
607         fc_exact &= !sticky;
608
609         fc_exact &= normalize(result, result, sticky);
610 }
611
612 /**
613  * calculate a / b
614  */
615 static void _fdiv(const fp_value *a, const fp_value *b, fp_value *result) {
616         int sticky;
617         char *temp, *dividend;
618         char res_sign;
619
620         fc_exact = 1;
621
622         handle_NAN(a, b, result);
623
624         temp = alloca(value_size);
625         dividend = alloca(value_size);
626
627         if (result != a && result != b)
628                 result->desc = a->desc;
629
630         result->sign = res_sign = a->sign ^ b->sign;
631
632         /* produce NAN on 0/0 and inf/inf */
633         if (a->desc.clss == ZERO) {
634                 if (b->desc.clss == ZERO)
635                         /* 0/0 -> NaN */
636                         fc_get_qnan(&a->desc, result);
637                 else {
638                         /* 0/x -> a */
639                         if (a != result)
640                                 memcpy(result, a, calc_buffer_size);
641                         result->sign = res_sign;
642                 }
643                 return;
644         }
645
646         if (b->desc.clss == INF) {
647                 if (a->desc.clss == INF)
648                         /* inf/inf -> NaN */
649                         fc_get_qnan(&a->desc, result);
650                 else {
651                         /* x/inf -> 0 */
652                         sc_val_from_ulong(0, NULL);
653                         _save_result(_exp(result));
654                         _save_result(_mant(result));
655                         result->desc.clss = ZERO;
656                 }
657                 return;
658         }
659
660         if (a->desc.clss == INF) {
661                 /* inf/x -> inf */
662                 if (a != result)
663                         memcpy(result, a, calc_buffer_size);
664                 result->sign = res_sign;
665                 return;
666         }
667         if (b->desc.clss == ZERO) {
668                 /* division by zero */
669                 if (result->sign)
670                         fc_get_minusinf(&a->desc, result);
671                 else
672                         fc_get_plusinf(&a->desc, result);
673                 return;
674         }
675
676         /* exp = exp(a) - exp(b) + excess - 1*/
677         sc_sub(_exp(a), _exp(b), _exp(result));
678         sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 2, temp);
679         sc_add(_exp(result), temp, _exp(result));
680
681         /* mixed normal, subnormal values introduce an error of 1, correct it */
682         if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
683                 sc_val_from_ulong(1, temp);
684                 sc_add(_exp(result), temp, _exp(result));
685         }
686
687         /* mant(res) = mant(a) / 1/2mant(b) */
688         /* to gain more bits of precision in the result the dividend could be
689          * shifted left, as this operation does not loose bits. This would not
690          * fit into the integer precision, but due to the rounding bits (which
691          * are always zero because the values are all normalized) the divisor
692          * can be shifted right instead to achieve the same result */
693         sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
694
695         _shift_left(_mant(a), temp, dividend);
696
697         {
698                 char *divisor = alloca(calc_buffer_size);
699                 sc_val_from_ulong(1, divisor);
700                 _shift_right(_mant(b), divisor, divisor);
701                 sc_div(dividend, divisor, _mant(result));
702                 sticky = sc_had_carry();
703                 fc_exact &= !sticky;
704         }
705
706         fc_exact &= normalize(result, result, sticky);
707 }
708
709 #if 0
710 static void _power_of_ten(int exp, ieee_descriptor_t *desc, char *result) {
711         char *build;
712         char *temp;
713
714         /* positive sign */
715         result->sign = 0;
716
717         /* set new descriptor (else result is supposed to already have one) */
718         if (desc != NULL)
719                 result->desc = *desc;
720
721         build = alloca(value_size);
722         temp = alloca(value_size);
723
724         sc_val_from_ulong((1 << (result->desc.exponent_size - 1)) - 1, _exp(result));
725
726         if (exp > 0) {
727                 /* temp is value of ten now */
728                 sc_val_from_ulong(10, NULL);
729                 _save_result(temp);
730
731                 for (exp--; exp > 0; exp--) {
732                         _save_result(build);
733                         sc_mul(build, temp, NULL);
734                 }
735                 _save_result(build);
736
737                 /* temp is amount of left shift needed to put the value left of the radix point */
738                 sc_val_from_ulong(result->desc.mantissa_size + ROUNDING_BITS, temp);
739
740                 _shift_left(build, temp, _mant(result));
741
742                 _normalize(result, result, 0);
743         }
744 }
745 #endif
746
747 /**
748  * Truncate the fractional part away.
749  *
750  * This does not clip to any integer range.
751  */
752 static void _trunc(const fp_value *a, fp_value *result) {
753         /*
754          * When exponent == 0 all bits left of the radix point
755          * are the integral part of the value. For 15bit exp_size
756          * this would require a left shift of max. 16383 bits which
757          * is too much.
758          * But it is enough to ensure that no bit right of the radix
759          * point remains set. This restricts the interesting
760          * exponents to the interval [0, mant_size-1].
761          * Outside this interval the truncated value is either 0 or
762          * it does not have fractional parts.
763          */
764
765         int exp_bias, exp_val;
766         char *temp;
767
768         /* fixme: can be exact */
769         fc_exact = 0;
770
771         temp = alloca(value_size);
772
773         if (a != result)
774                 result->desc = a->desc;
775
776         exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
777         exp_val  = sc_val_to_long(_exp(a)) - exp_bias;
778
779         if (exp_val < 0) {
780                 sc_val_from_ulong(0, NULL);
781                 _save_result(_exp(result));
782                 _save_result(_mant(result));
783                 result->desc.clss = ZERO;
784
785                 return;
786         }
787
788         if (exp_val > a->desc.mantissa_size) {
789                 if (a != result)
790                         memcpy(result, a, calc_buffer_size);
791
792                 return;
793         }
794
795         /* set up a proper mask to delete all bits right of the
796          * radix point if the mantissa had been shifted until exp == 0 */
797         sc_max_from_bits(1 + exp_val, 0, temp);
798         sc_val_from_long(a->desc.mantissa_size - exp_val + 2, NULL);
799         _shift_left(temp, sc_get_buffer(), temp);
800
801         /* and the mask and return the result */
802         sc_and(_mant(a), temp, _mant(result));
803
804         if (a != result) memcpy(_exp(result), _exp(a), value_size);
805 }
806
807 /********
808  * functions defined in fltcalc.h
809  ********/
810 const void *fc_get_buffer(void) {
811         return calc_buffer;
812 }
813
814 int fc_get_buffer_length(void) {
815         return calc_buffer_size;
816 }
817
818 void *fc_val_from_str(const char *str, unsigned int len, const ieee_descriptor_t *desc, void *result) {
819 #if 0
820         enum {
821                 START,
822                 LEFT_OF_DOT,
823                 RIGHT_OF_DOT,
824                 EXP_START,
825                 EXPONENT,
826                 END
827         };
828
829         char exp_sign;
830         int exp_int, hsb, state;
831
832         const char *old_str;
833
834         int pos;
835         char *mant_str, *exp_val, *power_val;
836
837         (void) len;
838         if (result == NULL) result = calc_buffer;
839
840         exp_val = alloca(value_size);
841         power_val = alloca(calc_buffer_size);
842         mant_str = alloca((len)?(len):(strlen(str)));
843
844         result->desc.exponent_size = desc->exponent_size;
845         result->desc.mantissa_size = desc->mantissa_size;
846         result->desc.explicit_one  = desc->explicit_one;
847         result->desc.clss          = NORMAL;
848
849         old_str = str;
850         pos = 0;
851         exp_int = 0;
852         state = START;
853
854         while (len == 0 || str-old_str < len) {
855                 switch (state) {
856                 case START:
857                         switch (*str) {
858                         case '+':
859                                 result->sign = 0;
860                                 state = LEFT_OF_DOT;
861                                 str++;
862                                 break;
863
864                         case '-':
865                                 result->sign = 1;
866                                 state = LEFT_OF_DOT;
867                                 str++;
868                                 break;
869
870                         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
871                                 result->sign = 0;
872                                 state = LEFT_OF_DOT;
873                                 break;
874
875                         case '.':
876                                 result->sign = 0;
877                                 state = RIGHT_OF_DOT;
878                                 str++;
879                                 break;
880
881                         case 'n':
882                         case 'N':
883                         case 'i':
884                         case 'I':
885                                 break;
886
887                         default:
888                                 fail_char(old_str, len, str - old_str);
889                         }
890                         break;
891
892                 case LEFT_OF_DOT:
893                         switch (*str) {
894                         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
895                                 mant_str[pos++] = *(str++);
896                                 break;
897
898                         case '.':
899                                 state = RIGHT_OF_DOT;
900                                 str++;
901                                 break;
902
903                         case 'e':
904                         case 'E':
905                                 state = EXP_START;
906                                 str++;
907                                 break;
908
909                         case '\0':
910                                 mant_str[pos] = '\0';
911                                 goto done;
912
913                         default:
914                                 fail_char(old_str, len, str - old_str);
915                         }
916                         break;
917
918                 case RIGHT_OF_DOT:
919                         switch (*str) {
920                         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
921                                 mant_str[pos++] = *(str++);
922                                 exp_int++;
923                                 break;
924
925                         case 'e':
926                         case 'E':
927                                 state = EXP_START;
928                                 str++;
929                                 break;
930
931                         case '\0':
932                                 mant_str[pos] = '\0';
933                                 goto done;
934
935                         default:
936                                 fail_char(old_str, len, str - old_str);
937                         }
938                         break;
939
940                 case EXP_START:
941                         switch (*str) {
942                         case '-':
943                                 exp_sign = 1;
944                                 /* fall through */
945                         case '+':
946                                 if (*(str-1) != 'e' && *(str-1) != 'E') fail_char(old_str, len, str - old_str);
947                                 str++;
948                                 break;
949
950                         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
951                                 mant_str[pos] = '\0';
952                                 pos = 1;
953                                 str++;
954                                 state = EXPONENT;
955                                 break;
956
957                         default:
958                                 fail_char(old_str, len, str - old_str);
959                         }
960                         break;
961
962                 case EXPONENT:
963                         switch (*str) {
964                         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
965                                 pos++;
966                                 str++;
967                                 break;
968
969                         case '\0': goto done;
970
971                         default:
972                                 fail_char(old_str, len, str - old_str);
973                         }
974                 }
975         } /*  switch(state) */
976
977 done:
978         sc_val_from_str(mant_str, strlen(mant_str), _mant(result));
979
980         /* shift to put value left of radix point */
981         sc_val_from_ulong(mant_size + ROUNDING_BITS, exp_val);
982
983         _shift_left(_mant(result), exp_val, _mant(result));
984
985         sc_val_from_ulong((1 << (exp_size - 1)) - 1, _exp(result));
986
987         _normalize(result, result, 0);
988
989         if (state == EXPONENT) {
990                 exp_int -= atoi(str-pos);
991         }
992
993         _power_of_ten(exp_int, &result->desc, power_val);
994
995         _fdiv(result, power_val, result);
996
997         return result;
998 #else
999         /* XXX excuse of an implementation to make things work */
1000         LLDBL             val;
1001         fp_value          *tmp = alloca(calc_buffer_size);
1002         ieee_descriptor_t tmp_desc;
1003         (void) len;
1004         (void) desc;
1005
1006 #ifdef HAVE_LONG_DOUBLE
1007         val = strtold(str, NULL);
1008         DEBUGPRINTF(("val_from_str(%s)\n", str));
1009         tmp_desc.exponent_size = 15;
1010         tmp_desc.mantissa_size = 63;
1011         tmp_desc.explicit_one  = 1;
1012         tmp_desc.clss          = NORMAL;
1013         fc_val_from_ieee754(val, &tmp_desc, tmp);
1014 #else
1015         val = strtod(str, NULL);
1016         DEBUGPRINTF(("val_from_str(%s)\n", str));
1017         tmp_desc.exponent_size = 11;
1018         tmp_desc.mantissa_size = 52;
1019         tmp_desc.explicit_one  = 0;
1020         tmp_desc.clss          = NORMAL;
1021         fc_val_from_ieee754(val, &tmp_desc, tmp);
1022 #endif /* HAVE_LONG_DOUBLE */
1023         return fc_cast(tmp, &tmp_desc, result);
1024 #endif
1025 }
1026
1027 fp_value *fc_val_from_ieee754(LLDBL l, const ieee_descriptor_t *desc, fp_value *result) {
1028         char *temp;
1029         int bias_res, bias_val, mant_val;
1030         value_t srcval;
1031         UINT32 sign, exponent, mantissa0, mantissa1;
1032
1033         srcval.d = l;
1034         bias_res = ((1 << (desc->exponent_size - 1)) - 1);
1035
1036 #ifdef HAVE_LONG_DOUBLE
1037         mant_val  = 63;
1038         bias_val  = 0x3fff;
1039         sign      = (srcval.val.high & 0x00008000) != 0;
1040         exponent  = (srcval.val.high & 0x00007FFF) ;
1041         mantissa0 = srcval.val.mid;
1042         mantissa1 = srcval.val.low;
1043 #else /* no long double */
1044         mant_val  = 52;
1045         bias_val  = 0x3ff;
1046         sign      = (srcval.val.high & 0x80000000) != 0;
1047         exponent  = (srcval.val.high & 0x7FF00000) >> 20;
1048         mantissa0 = srcval.val.high & 0x000FFFFF;
1049         mantissa1 = srcval.val.low;
1050 #endif
1051
1052 #ifdef HAVE_LONG_DOUBLE
1053         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)); */
1054         DEBUGPRINTF(("(%d-%.4X-%.8X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1055 #else
1056         TRACEPRINTF(("val_from_float(%.8X%.8X)\n", srcval.val.high, srcval.val.low));
1057         DEBUGPRINTF(("(%d-%.3X-%.5X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1058 #endif
1059
1060         if (result == NULL) result = calc_buffer;
1061         temp = alloca(value_size);
1062
1063         /* CLEAR the buffer, else some bits might be uninitialized */
1064         memset(result, 0, fc_get_buffer_length());
1065
1066         result->desc.exponent_size = desc->exponent_size;
1067         result->desc.mantissa_size = desc->mantissa_size;
1068         result->desc.explicit_one  = desc->explicit_one;
1069
1070         /* extract sign */
1071         result->sign = sign;
1072
1073         /* sign and flag suffice to identify NaN or inf, no exponent/mantissa
1074          * encoding is needed. the function can return immediately in these cases */
1075         if (isnan(l)) {
1076                 result->desc.clss = NAN;
1077                 TRACEPRINTF(("val_from_float resulted in NAN\n"));
1078                 return result;
1079         }
1080         else if (isinf(l)) {
1081                 result->desc.clss = INF;
1082                 TRACEPRINTF(("val_from_float resulted in %sINF\n", (result->sign == 1) ? "-" : ""));
1083                 return result;
1084         }
1085
1086         /* build exponent, because input and output exponent and mantissa sizes may differ
1087          * this looks more complicated than it is: unbiased input exponent + output bias,
1088          * minus the mantissa difference which is added again later when the output float
1089          * becomes normalized */
1090         sc_val_from_long((exponent - bias_val + bias_res) - (mant_val - desc->mantissa_size), _exp(result));
1091
1092         /* build mantissa representation */
1093         if (exponent != 0) {
1094                 /* insert the hidden bit */
1095                 sc_val_from_ulong(1, temp);
1096                 sc_val_from_ulong(mant_val + ROUNDING_BITS, NULL);
1097                 _shift_left(temp, sc_get_buffer(), NULL);
1098         }
1099         else {
1100                 sc_val_from_ulong(0, NULL);
1101         }
1102
1103         _save_result(_mant(result));
1104
1105         /* bits from the upper word */
1106         sc_val_from_ulong(mantissa0, temp);
1107         sc_val_from_ulong(34, NULL);
1108         _shift_left(temp, sc_get_buffer(), temp);
1109         sc_or(_mant(result), temp, _mant(result));
1110
1111         /* bits from the lower word */
1112         sc_val_from_ulong(mantissa1, temp);
1113         sc_val_from_ulong(ROUNDING_BITS, NULL);
1114         _shift_left(temp, sc_get_buffer(), temp);
1115         sc_or(_mant(result), temp, _mant(result));
1116
1117         /* _normalize expects the radix point to be normal, so shift mantissa of subnormal
1118          * origin one to the left */
1119         if (exponent == 0) {
1120                 sc_val_from_ulong(1, NULL);
1121                 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1122         }
1123
1124         normalize(result, result, 0);
1125
1126         TRACEPRINTF(("val_from_float results in %s\n", fc_print(result, temp, calc_buffer_size, FC_PACKED)));
1127
1128         return result;
1129 }
1130
1131 LLDBL fc_val_to_ieee754(const fp_value *val) {
1132         fp_value *value;
1133         fp_value *temp = NULL;
1134
1135         int byte_offset;
1136
1137         UINT32 sign;
1138         UINT32 exponent;
1139         UINT32 mantissa0;
1140         UINT32 mantissa1;
1141
1142         value_t           buildval;
1143         ieee_descriptor_t desc;
1144
1145 #ifdef HAVE_LONG_DOUBLE
1146         desc.exponent_size = 15;
1147         desc.mantissa_size = 63;
1148         desc.explicit_one  = 1;
1149         desc.clss          = NORMAL;
1150 #else
1151         desc.exponent_size = 11;
1152         desc.mantissa_size = 52;
1153         desc.explicit_one  = 0;
1154         desc.clss          = NORMAL;
1155 #endif
1156
1157         temp = alloca(calc_buffer_size);
1158         value = fc_cast(val, &desc, temp);
1159
1160         sign = value->sign;
1161
1162         /* @@@ long double exponent is 15bit, so the use of sc_val_to_long should not
1163          * lead to wrong results */
1164         exponent = sc_val_to_long(_exp(value)) ;
1165
1166         sc_val_from_ulong(ROUNDING_BITS, NULL);
1167         _shift_right(_mant(value), sc_get_buffer(), _mant(value));
1168
1169         mantissa0 = 0;
1170         mantissa1 = 0;
1171
1172         for (byte_offset = 0; byte_offset < 4; byte_offset++)
1173                 mantissa1 |= sc_sub_bits(_mant(value), desc.mantissa_size, byte_offset) << (byte_offset<<3);
1174
1175         for (; (byte_offset<<3) < desc.mantissa_size; byte_offset++)
1176                 mantissa0 |= sc_sub_bits(_mant(value), desc.mantissa_size, byte_offset) << ((byte_offset-4)<<3);
1177
1178 #ifdef HAVE_LONG_DOUBLE
1179         buildval.val.high = sign << 15;
1180         buildval.val.high |= exponent;
1181         buildval.val.mid = mantissa0;
1182         buildval.val.low = mantissa1;
1183 #else /* no long double */
1184         mantissa0 &= 0x000FFFFF;  /* get rid of garbage */
1185         buildval.val.high = sign << 31;
1186         buildval.val.high |= exponent << 20;
1187         buildval.val.high |= mantissa0;
1188         buildval.val.low = mantissa1;
1189 #endif
1190
1191         TRACEPRINTF(("val_to_float: %d-%x-%x%x\n", sign, exponent, mantissa0, mantissa1));
1192         return buildval.d;
1193 }
1194
1195 fp_value *fc_cast(const fp_value *value, const ieee_descriptor_t *desc, fp_value *result) {
1196         char *temp;
1197         int exp_offset, val_bias, res_bias;
1198
1199         if (result == NULL) result = calc_buffer;
1200         temp = alloca(value_size);
1201
1202         if (value->desc.exponent_size == desc->exponent_size &&
1203                 value->desc.mantissa_size == desc->mantissa_size &&
1204                 value->desc.explicit_one  == desc->explicit_one) {
1205                 if (value != result)
1206                         memcpy(result, value, calc_buffer_size);
1207                 return result;
1208         }
1209
1210         if (value->desc.clss == NAN) {
1211                 if (sc_get_highest_set_bit(_mant(value)) == value->desc.mantissa_size + 1)
1212                         return fc_get_qnan(desc, result);
1213                 else
1214                         return fc_get_snan(desc, result);
1215         }
1216
1217         /* set the descriptor of the new value */
1218         result->desc.exponent_size = desc->exponent_size;
1219         result->desc.mantissa_size = desc->mantissa_size;
1220         result->desc.explicit_one  = desc->explicit_one;
1221         result->desc.clss          = value->desc.clss;
1222
1223         result->sign = value->sign;
1224
1225         /* when the mantissa sizes differ normalizing has to shift to align it.
1226          * this would change the exponent, which is unwanted. So calculate this
1227          * offset and add it */
1228         val_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1229         res_bias = (1 << (desc->exponent_size - 1)) - 1;
1230
1231         exp_offset = (res_bias - val_bias) - (value->desc.mantissa_size - desc->mantissa_size);
1232         sc_val_from_long(exp_offset, temp);
1233         sc_add(_exp(value), temp, _exp(result));
1234
1235         /* _normalize expects normalized radix point */
1236         if (value->desc.clss == SUBNORMAL) {
1237                 sc_val_from_ulong(1, NULL);
1238                 _shift_left(_mant(value), sc_get_buffer(), _mant(result));
1239         } else if (value != result) {
1240                 memcpy(_mant(result), _mant(value), value_size);
1241         } else {
1242                 memmove(_mant(result), _mant(value), value_size);
1243         }
1244
1245         normalize(result, result, 0);
1246         TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1247         return result;
1248 }
1249
1250 fp_value *fc_get_max(const ieee_descriptor_t *desc, fp_value *result) {
1251         if (result == NULL) result = calc_buffer;
1252
1253         result->desc.exponent_size = desc->exponent_size;
1254         result->desc.mantissa_size = desc->mantissa_size;
1255         result->desc.explicit_one  = desc->explicit_one;
1256         result->desc.clss          = NORMAL;
1257
1258         result->sign = 0;
1259
1260         sc_val_from_ulong((1 << desc->exponent_size) - 2, _exp(result));
1261
1262         sc_max_from_bits(desc->mantissa_size + 1, 0, _mant(result));
1263         sc_val_from_ulong(ROUNDING_BITS, NULL);
1264         _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1265
1266         return result;
1267 }
1268
1269 fp_value *fc_get_min(const ieee_descriptor_t *desc, fp_value *result) {
1270         if (result == NULL) result = calc_buffer;
1271
1272         fc_get_max(desc, result);
1273         result->sign = 1;
1274
1275         return result;
1276 }
1277
1278 fp_value *fc_get_snan(const ieee_descriptor_t *desc, fp_value *result) {
1279         if (result == NULL) result = calc_buffer;
1280
1281         result->desc.exponent_size = desc->exponent_size;
1282         result->desc.mantissa_size = desc->mantissa_size;
1283         result->desc.explicit_one  = desc->explicit_one;
1284         result->desc.clss          = NAN;
1285
1286         result->sign = 0;
1287
1288         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1289
1290         /* signaling NaN has non-zero mantissa with msb not set */
1291         sc_val_from_ulong(1, _mant(result));
1292
1293         return result;
1294 }
1295
1296 fp_value *fc_get_qnan(const ieee_descriptor_t *desc, fp_value *result) {
1297         if (result == NULL) result = calc_buffer;
1298
1299         result->desc.exponent_size = desc->exponent_size;
1300         result->desc.mantissa_size = desc->mantissa_size;
1301         result->desc.explicit_one  = desc->explicit_one;
1302         result->desc.clss          = NAN;
1303
1304         result->sign = 0;
1305
1306         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1307
1308         /* quiet NaN has the msb of the mantissa set, so shift one there */
1309         sc_val_from_ulong(1, _mant(result));
1310         /* mantissa_size >+< 1 because of two extra rounding bits */
1311         sc_val_from_ulong(desc->mantissa_size + 1, NULL);
1312         _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1313
1314         return result;
1315 }
1316
1317 fp_value *fc_get_plusinf(const ieee_descriptor_t *desc, fp_value *result) {
1318         if (result == NULL) result = calc_buffer;
1319
1320         result->desc.exponent_size = desc->exponent_size;
1321         result->desc.mantissa_size = desc->mantissa_size;
1322         result->desc.explicit_one  = desc->explicit_one;
1323         result->desc.clss          = NORMAL;
1324
1325         result->sign = 0;
1326
1327         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1328
1329         sc_val_from_ulong(0, _mant(result));
1330
1331         return result;
1332 }
1333
1334 fp_value *fc_get_minusinf(const ieee_descriptor_t *desc, fp_value *result) {
1335         if (result == NULL) result = calc_buffer;
1336
1337         fc_get_plusinf(desc, result);
1338         result->sign = 1;
1339
1340         return result;
1341 }
1342
1343 int fc_comp(const fp_value *val_a, const fp_value *val_b) {
1344         int mul = 1;
1345
1346         /*
1347          * shortcut: if both values are identical, they are either
1348          * Unordered if NaN or equal
1349          */
1350         if (val_a == val_b)
1351                 return val_a->desc.clss == NAN ? 2 : 0;
1352
1353         /* unordered if one is a NaN */
1354         if (val_a->desc.clss == NAN || val_b->desc.clss == NAN)
1355                 return 2;
1356
1357         /* zero is equal independent of sign */
1358         if ((val_a->desc.clss == ZERO) && (val_b->desc.clss == ZERO))
1359                 return 0;
1360
1361         /* different signs make compare easy */
1362         if (val_a->sign != val_b->sign)
1363                 return (val_a->sign == 0) ? (1) : (-1);
1364
1365         mul = val_a->sign ? -1 : 1;
1366
1367         /* both infinity means equality */
1368         if ((val_a->desc.clss == INF) && (val_b->desc.clss == INF))
1369                 return 0;
1370
1371         /* infinity is bigger than the rest */
1372         if (val_a->desc.clss == INF)
1373                 return  1 * mul;
1374         if (val_b->desc.clss == INF)
1375                 return -1 * mul;
1376
1377         /* check first exponent, that mantissa if equal */
1378         switch (sc_comp(_exp(val_a), _exp(val_b))) {
1379         case -1:
1380                 return -1 * mul;
1381         case  1:
1382                 return  1 * mul;
1383         case  0:
1384                 return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1385         default:
1386                 return 2;
1387         }
1388 }
1389
1390 int fc_is_zero(const fp_value *a) {
1391         return a->desc.clss == ZERO;
1392 }
1393
1394 int fc_is_negative(const fp_value *a) {
1395         return a->sign;
1396 }
1397
1398 int fc_is_inf(const fp_value *a) {
1399         return a->desc.clss == INF;
1400 }
1401
1402 int fc_is_nan(const fp_value *a) {
1403         return a->desc.clss == NAN;
1404 }
1405
1406 int fc_is_subnormal(const fp_value *a) {
1407         return a->desc.clss == SUBNORMAL;
1408 }
1409
1410 char *fc_print(const fp_value *val, char *buf, int buflen, unsigned base) {
1411         char *mul_1;
1412
1413         mul_1 = alloca(calc_buffer_size);
1414
1415         switch (base) {
1416         case FC_DEC:
1417                 switch ((value_class_t)val->desc.clss) {
1418                 case INF:
1419                         if (buflen >= 8 + val->sign) sprintf(buf, "%sINFINITY", val->sign ? "-":"");
1420                         else snprintf(buf, buflen, "%sINF", val->sign ? "-":NULL);
1421                         break;
1422                 case NAN:
1423                         snprintf(buf, buflen, "NAN");
1424                         break;
1425                 case ZERO:
1426                         snprintf(buf, buflen, "0.0");
1427                         break;
1428                 default:
1429                         /* XXX to be implemented */
1430 #ifdef HAVE_LONG_DOUBLE
1431                         /* XXX 30 is arbitrary */
1432                         snprintf(buf, buflen, "%.30LE", fc_val_to_ieee754(val));
1433 #else
1434                         snprintf(buf, buflen, "%.18E", fc_val_to_ieee754(val));
1435 #endif
1436                 }
1437                 break;
1438
1439         case FC_HEX:
1440                 switch ((value_class_t)val->desc.clss) {
1441                 case INF:
1442                         if (buflen >= 8+val->sign) sprintf(buf, "%sINFINITY", val->sign?"-":"");
1443                         else snprintf(buf, buflen, "%sINF", val->sign?"-":NULL);
1444                         break;
1445                 case NAN:
1446                         snprintf(buf, buflen, "NAN");
1447                         break;
1448                 case ZERO:
1449                         snprintf(buf, buflen, "0.0");
1450                         break;
1451                 default:
1452 #ifdef HAVE_LONG_DOUBLE
1453                         snprintf(buf, buflen, "%LA", fc_val_to_ieee754(val));
1454 #else
1455                         snprintf(buf, buflen, "%A", fc_val_to_ieee754(val));
1456 #endif
1457                 }
1458                 break;
1459
1460         case FC_PACKED:
1461         default:
1462                 snprintf(buf, buflen, "%s", sc_print(pack(val, mul_1), value_size*4, SC_HEX, 0));
1463                 buf[buflen - 1] = '\0';
1464                 break;
1465         }
1466         return buf;
1467 }
1468
1469 unsigned char fc_sub_bits(const fp_value *value, unsigned num_bits, unsigned byte_ofs) {
1470         /* this is used to cache the packed version of the value */
1471         static char *packed_value = NULL;
1472
1473         if (packed_value == NULL) packed_value = xmalloc(value_size);
1474
1475         if (value != NULL)
1476                 pack(value, packed_value);
1477
1478         return sc_sub_bits(packed_value, num_bits, byte_ofs);
1479 }
1480
1481 /* Returns non-zero if the mantissa is zero, i.e. 1.0Exxx */
1482 int fc_zero_mantissa(const fp_value *value) {
1483         return sc_get_lowest_set_bit(_mant(value)) == ROUNDING_BITS + value->desc.mantissa_size;
1484 }
1485
1486 /* Returns the exponent of a value. */
1487 int fc_get_exponent(const fp_value *value) {
1488         int exp_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1489         return sc_val_to_long(_exp(value)) - exp_bias;
1490 }
1491
1492 /* Return non-zero if a given value can be converted lossless into another precision */
1493 int fc_can_lossless_conv_to(const fp_value *value, char exp_size, char mant_size) {
1494         int v;
1495         int exp_bias;
1496
1497         /* handle some special cases first */
1498         switch (value->desc.clss) {
1499         case ZERO:
1500         case INF:
1501         case NAN:
1502                 return 1;
1503         default:
1504                 break;
1505         }
1506
1507         /* check if the exponent can be encoded: note, 0 and all ones are reserved for the exponent */
1508         exp_bias = (1 << (exp_size - 1)) - 1;
1509         v = fc_get_exponent(value) + exp_bias;
1510         if (0 < v && v < (1 << exp_size) - 1) {
1511                 /* check the mantissa */
1512                 v = value->desc.mantissa_size + ROUNDING_BITS - sc_get_lowest_set_bit(_mant(value));
1513                 return v < mant_size;
1514         }
1515         return 0;
1516 }
1517
1518
1519 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode) {
1520         if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1521                 rounding_mode = mode;
1522
1523         return rounding_mode;
1524 }
1525
1526 fc_rounding_mode_t fc_get_rounding_mode(void) {
1527         return rounding_mode;
1528 }
1529
1530 void init_fltcalc(int precision) {
1531         if (calc_buffer == NULL) {
1532                 /* does nothing if already init */
1533                 if (precision == 0) precision = FC_DEFAULT_PRECISION;
1534
1535                 init_strcalc(precision + 4);
1536
1537                 /* needs additionally two bits to round, a bit as explicit 1., and one for
1538                  * addition overflow */
1539                 max_precision = sc_get_precision() - 4;
1540                 if (max_precision < precision)
1541                         printf("WARNING: not enough precision available, using %d\n", max_precision);
1542
1543                 rounding_mode    = FC_TONEAREST;
1544                 value_size       = sc_get_buffer_length();
1545                 calc_buffer_size = sizeof(fp_value) + 2*value_size - 1;
1546
1547                 calc_buffer = xmalloc(calc_buffer_size);
1548                 memset(calc_buffer, 0, calc_buffer_size);
1549                 DEBUGPRINTF(("init fltcalc:\n\tVALUE_SIZE = %d\ntCALC_BUFFER_SIZE = %d\n\tcalc_buffer = %p\n\n", value_size, calc_buffer_size, calc_buffer));
1550 #ifdef HAVE_LONG_DOUBLE
1551                 DEBUGPRINTF(("\tUsing long double (1-15-64) interface\n"));
1552 #else
1553                 DEBUGPRINTF(("\tUsing double (1-11-52) interface\n"));
1554 #endif
1555 #ifdef WORDS_BIGENDIAN
1556                 DEBUGPRINTF(("\tWord order is big endian\n\n"));
1557 #else
1558                 DEBUGPRINTF(("\tWord order is little endian\n\n"));
1559 #endif
1560         }
1561 }
1562
1563 void finish_fltcalc (void) {
1564         free(calc_buffer); calc_buffer = NULL;
1565 }
1566
1567 #ifdef FLTCALC_TRACE_CALC
1568 static char buffer[100];
1569 #endif
1570
1571 /* definition of interface functions */
1572 fp_value *fc_add(const fp_value *a, const fp_value *b, fp_value *result) {
1573         if (result == NULL) result = calc_buffer;
1574
1575         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1576         TRACEPRINTF(("+ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1577
1578         /* make the value with the bigger exponent the first one */
1579         if (sc_comp(_exp(a), _exp(b)) == -1)
1580                 _fadd(b, a, result);
1581         else
1582                 _fadd(a, b, result);
1583
1584         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1585         return result;
1586 }
1587
1588 fp_value *fc_sub(const fp_value *a, const fp_value *b, fp_value *result) {
1589         fp_value *temp;
1590
1591         if (result == NULL) result = calc_buffer;
1592
1593         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1594         TRACEPRINTF(("- %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1595
1596         temp = alloca(calc_buffer_size);
1597         memcpy(temp, b, calc_buffer_size);
1598         temp->sign = !b->sign;
1599         if (sc_comp(_exp(a), _exp(temp)) == -1)
1600                 _fadd(temp, a, result);
1601         else
1602                 _fadd(a, temp, result);
1603
1604         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1605         return result;
1606 }
1607
1608 fp_value *fc_mul(const fp_value *a, const fp_value *b, fp_value *result) {
1609         if (result == NULL) result = calc_buffer;
1610
1611         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1612         TRACEPRINTF(("* %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1613
1614         _fmul(a, b, result);
1615
1616         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1617         return result;
1618 }
1619
1620 fp_value *fc_div(const fp_value *a, const fp_value *b, fp_value *result) {
1621         if (result == NULL) result = calc_buffer;
1622
1623         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1624         TRACEPRINTF(("/ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1625
1626         _fdiv(a, b, result);
1627
1628         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1629         return result;
1630 }
1631
1632 fp_value *fc_neg(const fp_value *a, fp_value *result) {
1633         if (result == NULL) result = calc_buffer;
1634
1635         TRACEPRINTF(("- %s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1636
1637         if (a != result)
1638                 memcpy(result, a, calc_buffer_size);
1639         result->sign = !a->sign;
1640
1641         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1642         return result;
1643 }
1644
1645 fp_value *fc_int(const fp_value *a, fp_value *result) {
1646         if (result == NULL) result = calc_buffer;
1647
1648         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1649         TRACEPRINTF(("truncated to integer "));
1650
1651         _trunc(a, result);
1652
1653         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1654         return result;
1655 }
1656
1657 fp_value *fc_rnd(const fp_value *a, fp_value *result) {
1658         if (result == NULL) result = calc_buffer;
1659
1660         (void) a;
1661         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1662         TRACEPRINTF(("rounded to integer "));
1663
1664         assert(!"fc_rnd() not yet implemented");
1665
1666         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1667         return result;
1668 }
1669
1670 /*
1671  * convert a floating point value into an sc value ...
1672  */
1673 int fc_flt2int(const fp_value *a, void *result, ir_mode *dst_mode) {
1674         if (a->desc.clss == NORMAL) {
1675                 int exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
1676                 int exp_val  = sc_val_to_long(_exp(a)) - exp_bias;
1677                 int shift, highest;
1678
1679                 if (a->sign && !mode_is_signed(dst_mode)) {
1680                         /* FIXME: for now we cannot convert this */
1681                         return 0;
1682                 }
1683
1684                 assert(exp_val >= 0 && "floating point value not integral before fc_flt2int() call");
1685                 shift = exp_val - (a->desc.mantissa_size + ROUNDING_BITS);
1686
1687                 if (shift > 0) {
1688                         sc_shlI(_mant(a),  shift, 64, 0, result);
1689                 } else {
1690                         sc_shrI(_mant(a), -shift, 64, 0, result);
1691                 }
1692
1693                 /* check for overflow */
1694                 highest = sc_get_highest_set_bit(result);
1695
1696                 if (mode_is_signed(dst_mode)) {
1697                         if (highest == sc_get_lowest_set_bit(result)) {
1698                                 /* need extra test for MIN_INT */
1699                                 if (highest >= (int) get_mode_size_bits(dst_mode)) {
1700                                         /* FIXME: handle overflow */
1701                                         return 0;
1702                                 }
1703                         } else {
1704                                 if (highest >= (int) get_mode_size_bits(dst_mode) - 1) {
1705                                         /* FIXME: handle overflow */
1706                                         return 0;
1707                                 }
1708                         }
1709                 } else {
1710                         if (highest >= (int) get_mode_size_bits(dst_mode)) {
1711                                 /* FIXME: handle overflow */
1712                                 return 0;
1713                         }
1714                 }
1715
1716                 if (a->sign)
1717                         sc_neg(result, result);
1718
1719                 return 1;
1720         }
1721         else if (a->desc.clss == ZERO) {
1722                 sc_zero(result);
1723                 return 1;
1724         }
1725         return 0;
1726 }
1727
1728
1729 unsigned fc_set_immediate_precision(unsigned bits) {
1730         unsigned old = immediate_prec;
1731
1732         immediate_prec = bits;
1733         return old;
1734 }
1735
1736 int fc_is_exact(void) {
1737         return fc_exact;
1738 }