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