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