Add get_tarval_lowest_bit() and get_tarval_popcnt(), expand some documentation.
[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 #include "config.h"
28
29 #include "fltcalc.h"
30 #include "strcalc.h"
31
32 #include <math.h>
33 /* undef some reused constants defined by math.h */
34 #ifdef NAN
35 #  undef NAN
36 #endif
37
38 #include <inttypes.h>
39 #include <string.h>
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <assert.h>
43
44 #include "xmalloc.h"
45
46 /** The number of extra precision rounding bits */
47 #define ROUNDING_BITS 2
48
49 typedef uint32_t UINT32;
50
51 #ifdef HAVE_LONG_DOUBLE
52 #ifdef WORDS_BIGENDIAN
53 typedef union {
54         struct {
55                 UINT32 high;
56                 UINT32 mid;
57                 UINT32 low;
58         } val;
59         volatile long double d;
60 } value_t;
61 #else
62 typedef union {
63         struct {
64                 UINT32 low;
65                 UINT32 mid;
66                 UINT32 high;
67         } val;
68         volatile long double d;
69 } value_t;
70 #endif
71 #else
72 #ifdef WORDS_BIGENDIAN
73 typedef union {
74         struct {
75                 UINT32 high;
76                 UINT32 low;
77         } val;
78         volatile double d;
79 } value_t;
80 #else
81 typedef union {
82         struct {
83                 UINT32 low;
84                 UINT32 high;
85         } val;
86         volatile double d;
87 } value_t;
88 #endif
89 #endif
90
91 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
92
93 /* our floating point value */
94 struct _fp_value {
95         ieee_descriptor_t desc;
96         char sign;
97         char value[1];                  /* exp[value_size] + mant[value_size] */
98 };
99
100 #define _exp(a)  &((a)->value[0])
101 #define _mant(a) &((a)->value[value_size])
102
103 #define _save_result(x) memcpy((x), sc_get_buffer(), value_size)
104 #define _shift_right(x, y, res) sc_shr((x), (y), value_size*4, 0, (res))
105 #define _shift_left(x, y, res) sc_shl((x), (y), value_size*4, 0, (res))
106
107
108 #ifdef FLTCALC_DEBUG
109 #  define DEBUGPRINTF(x) printf x
110 #else
111 #  define DEBUGPRINTF(x) ((void)0)
112 #endif
113
114 #ifdef FLTCALC_TRACE_CALC
115 #  define TRACEPRINTF(x) printf x
116 #else
117 #  define TRACEPRINTF(x) ((void)0)
118 #endif
119
120 /** The immediate precision. */
121 static unsigned immediate_prec = 0;
122
123 /** A temporal buffer. */
124 static fp_value *calc_buffer = NULL;
125
126 /** Current rounding mode.*/
127 static fc_rounding_mode_t rounding_mode;
128
129 static int calc_buffer_size;
130 static int value_size;
131 static int max_precision;
132
133 /** Exact flag. */
134 static int fc_exact = 1;
135
136 #if 0
137 static void fail_char(const char *str, unsigned int len, int pos) {
138         if (*(str+pos))
139                 printf("ERROR: Unexpected character '%c'\n", *(str + pos));
140         else
141                 printf("ERROR: Unexpected end of string\n");
142         while (len-- && *str) printf("%c", *str++); printf("\n");
143         while (pos--) printf(" "); printf("^\n");
144         /* the front end has to to check constant strings */
145         exit(-1);
146 }
147 #endif
148
149 /** pack machine-like */
150 static void *pack(const fp_value *int_float, void *packed) {
151         char     *shift_val;
152         char     *temp;
153         fp_value *val_buffer;
154         int      pos;
155
156         temp      = alloca(value_size);
157         shift_val = alloca(value_size);
158
159         switch ((value_class_t)int_float->desc.clss) {
160         case NAN:
161                 val_buffer = alloca(calc_buffer_size);
162                 fc_get_qnan(&int_float->desc, val_buffer);
163                 int_float = val_buffer;
164                 break;
165
166         case INF:
167                 val_buffer = alloca(calc_buffer_size);
168                 fc_get_plusinf(&int_float->desc, val_buffer);
169                 val_buffer->sign = int_float->sign;
170                 int_float = val_buffer;
171                 break;
172
173         default:
174                 break;
175         }
176         assert(int_float->desc.explicit_one <= 1);
177
178         /* pack sign: move it to the left after exponent AND mantissa */
179         sc_val_from_ulong(int_float->sign, temp);
180
181         pos = int_float->desc.exponent_size + int_float->desc.mantissa_size + int_float->desc.explicit_one;
182         sc_val_from_ulong(pos, NULL);
183         _shift_left(temp, sc_get_buffer(), packed);
184
185         /* pack exponent: move it to the left after mantissa */
186         pos = int_float->desc.mantissa_size + int_float->desc.explicit_one;
187         sc_val_from_ulong(pos, shift_val);
188         _shift_left(_exp(int_float), shift_val, temp);
189
190         /* combine sign|exponent */
191         sc_or(temp, packed, packed);
192
193         /* extract mantissa */
194         /* remove rounding bits */
195         sc_val_from_ulong(ROUNDING_BITS, shift_val);
196         _shift_right(_mant(int_float), shift_val, temp);
197
198         /* remove leading 1 (or 0 if denormalized) */
199         sc_max_from_bits(pos, 0, shift_val); /* all mantissa bits are 1's */
200         sc_and(temp, shift_val, temp);
201
202         /* combine sign|exponent|mantissa */
203         sc_or(temp, packed, packed);
204
205         return packed;
206 }
207
208 /**
209  * Normalize a fp_value.
210  *
211  * @return non-zero if result is exact
212  */
213 static int normalize(const fp_value *in_val, fp_value *out_val, int sticky) {
214         int exact = 1;
215         int hsb;
216         char lsb, guard, round, round_dir = 0;
217         char *temp = alloca(value_size);
218
219         /* save rounding bits at the end */
220         hsb = ROUNDING_BITS + in_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(in_val)) - 1;
221
222         if (in_val != out_val)   {
223                 out_val->sign = in_val->sign;
224                 memcpy(&out_val->desc, &in_val->desc, sizeof(out_val->desc));
225         }
226
227         out_val->desc.clss = NORMAL;
228
229         /* mantissa all zeros, so zero exponent (because of explicit one) */
230         if (hsb == ROUNDING_BITS + in_val->desc.mantissa_size)   {
231                 sc_val_from_ulong(0, _exp(out_val));
232                 hsb = -1;
233         }
234
235         /* shift the first 1 into the left of the radix point (i.e. hsb == -1) */
236         if (hsb < -1)   {
237                 /* shift right */
238                 sc_val_from_ulong(-hsb-1, temp);
239
240                 _shift_right(_mant(in_val), temp, _mant(out_val));
241
242                 /* remember if some bits were shifted away */
243                 if (sc_had_carry()) {
244                         exact = 0;
245                         sticky = 1;
246                 }
247                 sc_add(_exp(in_val), temp, _exp(out_val));
248         } else if (hsb > -1) {
249                 /* shift left */
250                 sc_val_from_ulong(hsb+1, temp);
251
252                 _shift_left(_mant(in_val), temp, _mant(out_val));
253
254                 sc_sub(_exp(in_val), temp, _exp(out_val));
255         }
256
257         /* check for exponent underflow */
258         if (sc_is_negative(_exp(out_val)) || sc_is_zero(_exp(out_val))) {
259                 DEBUGPRINTF(("Exponent underflow!\n"));
260                 /* exponent underflow */
261                 /* shift the mantissa right to have a zero exponent */
262                 sc_val_from_ulong(1, temp);
263                 sc_sub(temp, _exp(out_val), NULL);
264
265                 _shift_right(_mant(out_val), sc_get_buffer(), _mant(out_val));
266                 if (sc_had_carry()) {
267                         exact  = 0;
268                         sticky = 1;
269                 }
270                 /* denormalized means exponent of zero */
271                 sc_val_from_ulong(0, _exp(out_val));
272
273                 out_val->desc.clss = SUBNORMAL;
274         }
275
276         /* perform rounding by adding a value that clears the guard bit and the round bit
277          * and either causes a carry to round up or not */
278         /* get the last 3 bits of the value */
279         lsb = sc_sub_bits(_mant(out_val), out_val->desc.mantissa_size + ROUNDING_BITS, 0) & 0x7;
280         guard = (lsb&0x2)>>1;
281         round = lsb&0x1;
282
283         switch (rounding_mode) {
284         case FC_TONEAREST:
285                 /* round to nearest representable value, if in doubt choose the version
286                  * with lsb == 0 */
287                 round_dir = guard && (sticky || round || lsb>>2);
288                 break;
289         case FC_TOPOSITIVE:
290                 /* if positive: round to one if the exact value is bigger, else to zero */
291                 round_dir = (!out_val->sign && (guard || round || sticky));
292                 break;
293         case FC_TONEGATIVE:
294                 /* if negative: round to one if the exact value is bigger, else to zero */
295                 round_dir = (out_val->sign && (guard || round || sticky));
296                 break;
297         case FC_TOZERO:
298                 /* always round to 0 (chopping mode) */
299                 round_dir = 0;
300                 break;
301         }
302         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"));
303
304         if (round_dir == 1) {
305                 guard = (round^guard)<<1;
306                 lsb = !(round || guard)<<2 | guard | round;
307         } else {
308                 lsb = -((guard<<1) | round);
309         }
310
311         /* add the rounded value */
312         if (lsb != 0) {
313                 sc_val_from_long(lsb, temp);
314                 sc_add(_mant(out_val), temp, _mant(out_val));
315                 exact = 0;
316         }
317
318         /* could have rounded down to zero */
319         if (sc_is_zero(_mant(out_val)) && (out_val->desc.clss == SUBNORMAL))
320                 out_val->desc.clss = ZERO;
321
322         /* check for rounding overflow */
323         hsb = ROUNDING_BITS + out_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(out_val)) - 1;
324         if ((out_val->desc.clss != SUBNORMAL) && (hsb < -1)) {
325                 sc_val_from_ulong(1, temp);
326                 _shift_right(_mant(out_val), temp, _mant(out_val));
327                 if (exact && sc_had_carry())
328                         exact = 0;
329                 sc_add(_exp(out_val), temp, _exp(out_val));
330         } else if ((out_val->desc.clss == SUBNORMAL) && (hsb == -1)) {
331                 /* overflow caused the mantissa to be normal again,
332                  * so adapt the exponent accordingly */
333                 sc_val_from_ulong(1, temp);
334                 sc_add(_exp(out_val), temp, _exp(out_val));
335
336                 out_val->desc.clss = NORMAL;
337         }
338         /* no further rounding is needed, because rounding overflow means
339          * the carry of the original rounding was propagated all the way
340          * up to the bit left of the radix point. This implies the bits
341          * to the right are all zeros (rounding is +1) */
342
343         /* check for exponent overflow */
344         sc_val_from_ulong((1 << out_val->desc.exponent_size) - 1, temp);
345         if (sc_comp(_exp(out_val), temp) != -1) {
346                 DEBUGPRINTF(("Exponent overflow!\n"));
347                 /* exponent overflow, reaction depends on rounding method:
348                  *
349                  * mode        | sign of value |  result
350                  *--------------------------------------------------------------
351                  * TO_NEAREST  |      +        |   +inf
352                  *             |      -        |   -inf
353                  *--------------------------------------------------------------
354                  * TO_POSITIVE |      +        |   +inf
355                  *             |      -        |   smallest representable value
356                  *--------------------------------------------------------------
357                  * TO_NEAGTIVE |      +        |   largest representable value
358                  *             |      -        |   -inf
359                  *--------------------------------------------------------------
360                  * TO_ZERO     |      +        |   largest representable value
361                  *             |      -        |   smallest representable value
362                  *--------------------------------------------------------------*/
363                 if (out_val->sign == 0) {
364                         /* value is positive */
365                         switch (rounding_mode) {
366                         case FC_TONEAREST:
367                         case FC_TOPOSITIVE:
368                                 out_val->desc.clss = INF;
369                                 break;
370
371                         case FC_TONEGATIVE:
372                         case FC_TOZERO:
373                                 fc_get_max(&out_val->desc, out_val);
374                         }
375                 } else {
376                         /* value is negative */
377                         switch (rounding_mode) {
378                         case FC_TONEAREST:
379                         case FC_TONEGATIVE:
380                                 out_val->desc.clss = INF;
381                                 break;
382
383                         case FC_TOPOSITIVE:
384                         case FC_TOZERO:
385                                 fc_get_min(&out_val->desc, out_val);
386                         }
387                 }
388         }
389         return exact;
390 }
391
392 /**
393  * Operations involving NaN's must return NaN.
394  * They are NOT exact.
395  */
396 #define handle_NAN(a, b, result) \
397 do {                                                      \
398   if (a->desc.clss == NAN) {                              \
399     if (a != result) memcpy(result, a, calc_buffer_size); \
400     fc_exact = 0;                                         \
401     return;                                               \
402   }                                                       \
403   if (b->desc.clss == NAN) {                              \
404     if (b != result) memcpy(result, b, calc_buffer_size); \
405     fc_exact = 0;                                         \
406     return;                                               \
407   }                                                       \
408 }while (0)
409
410
411 /**
412  * calculate a + b, where a is the value with the bigger exponent
413  */
414 static void _fadd(const fp_value *a, const fp_value *b, fp_value *result) {
415         char *temp;
416         char *exp_diff;
417
418         char sign, res_sign;
419         char sticky;
420
421         fc_exact = 1;
422
423         handle_NAN(a, b, result);
424
425         /* make sure result has a descriptor */
426         if (result != a && result != b)
427                 result->desc = a->desc;
428
429         /* determine if this is an addition or subtraction */
430         sign = a->sign ^ b->sign;
431
432         /* produce NaN on inf - inf */
433         if (sign && (a->desc.clss == INF) && (b->desc.clss == INF)) {
434                 fc_exact = 0;
435                 fc_get_qnan(&a->desc, result);
436                 return;
437         }
438
439         temp     = alloca(value_size);
440         exp_diff = alloca(value_size);
441
442         /* get exponent difference */
443         sc_sub(_exp(a), _exp(b), exp_diff);
444
445         /* initially set sign to be the sign of a, special treatment of subtraction
446          * when exponents are equal is required though.
447          * Also special care about the sign is needed when the mantissas are equal
448          * (+/- 0 ?) */
449         if (sign && sc_val_to_long(exp_diff) == 0) {
450                 switch (sc_comp(_mant(a), _mant(b))) {
451                 case 1:  /* a > b */
452                         res_sign = a->sign;  /* abs(a) is bigger and a is negative */
453                         break;
454                 case 0:  /* a == b */
455                         res_sign = (rounding_mode == FC_TONEGATIVE);
456                         break;
457                 case -1: /* a < b */
458                         res_sign = b->sign; /* abs(b) is bigger and b is negative */
459                         break;
460                 default:
461                         /* can't be reached */
462                         res_sign = 0;
463                         break;
464                 }
465         }
466         else
467                 res_sign = a->sign;
468         result->sign = res_sign;
469
470         /* sign has been taken care of, check for special cases */
471         if (a->desc.clss == ZERO || b->desc.clss == INF) {
472                 if (b != result)
473                         memcpy(result, b, calc_buffer_size);
474                 fc_exact = b->desc.clss == NORMAL;
475                 result->sign = res_sign;
476                 return;
477         }
478         if (b->desc.clss == ZERO || a->desc.clss == INF) {
479                 if (a != result)
480                         memcpy(result, a, calc_buffer_size);
481                 fc_exact = a->desc.clss == NORMAL;
482                 result->sign = res_sign;
483                 return;
484         }
485
486         /* shift the smaller value to the right to align the radix point */
487         /* subnormals have their radix point shifted to the right,
488          * take care of this first */
489         if ((b->desc.clss == SUBNORMAL) && (a->desc.clss != SUBNORMAL)) {
490                 sc_val_from_ulong(1, temp);
491                 sc_sub(exp_diff, temp, exp_diff);
492         }
493
494         _shift_right(_mant(b), exp_diff, temp);
495         sticky = sc_had_carry();
496         fc_exact &= !sticky;
497
498         if (sticky && sign) {
499                 /* if subtracting a little more than the represented value or adding a little
500                  * more than the represented value to a negative value this, in addition to the
501                  * still set sticky bit, takes account of the 'little more' */
502                 char *temp1 = alloca(calc_buffer_size);
503                 sc_val_from_ulong(1, temp1);
504                 sc_add(temp, temp1, temp);
505         }
506
507         if (sign) {
508                 if (sc_comp(_mant(a), temp) == -1)
509                         sc_sub(temp, _mant(a), _mant(result));
510                 else
511                         sc_sub(_mant(a), temp, _mant(result));
512         } else {
513                 sc_add(_mant(a), temp, _mant(result));
514         }
515
516         /* _normalize expects a 'normal' radix point, adding two subnormals
517          * results in a subnormal radix point -> shifting before normalizing */
518         if ((a->desc.clss == SUBNORMAL) && (b->desc.clss == SUBNORMAL)) {
519                 sc_val_from_ulong(1, NULL);
520                 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
521         }
522
523         /* resulting exponent is the bigger one */
524         memmove(_exp(result), _exp(a), value_size);
525
526         fc_exact &= normalize(result, result, sticky);
527 }
528
529 /**
530  * calculate a * b
531  */
532 static void _fmul(const fp_value *a, const fp_value *b, fp_value *result) {
533         int sticky;
534         char *temp;
535         char res_sign;
536
537         fc_exact = 1;
538
539         handle_NAN(a, b, result);
540
541         temp = alloca(value_size);
542
543         if (result != a && result != b)
544                 result->desc = a->desc;
545
546         result->sign = res_sign = a->sign ^ b->sign;
547
548         /* produce NaN on 0 * inf */
549         if (a->desc.clss == ZERO) {
550                 if (b->desc.clss == INF) {
551                         fc_get_qnan(&a->desc, result);
552                         fc_exact = 0;
553                 } else {
554                         if (a != result)
555                                 memcpy(result, a, calc_buffer_size);
556                         result->sign = res_sign;
557                 }
558                 return;
559         }
560         if (b->desc.clss == ZERO) {
561                 if (a->desc.clss == INF) {
562                         fc_get_qnan(&a->desc, result);
563                         fc_exact = 0;
564                 } else {
565                         if (b != result)
566                                 memcpy(result, b, calc_buffer_size);
567                         result->sign = res_sign;
568                 }
569                 return;
570         }
571
572         if (a->desc.clss == INF) {
573                 fc_exact = 0;
574                 if (a != result)
575                         memcpy(result, a, calc_buffer_size);
576                 result->sign = res_sign;
577                 return;
578         }
579         if (b->desc.clss == INF) {
580                 fc_exact = 0;
581                 if (b != result)
582                         memcpy(result, b, calc_buffer_size);
583                 result->sign = res_sign;
584                 return;
585         }
586
587         /* exp = exp(a) + exp(b) - excess */
588         sc_add(_exp(a), _exp(b), _exp(result));
589
590         sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 1, temp);
591         sc_sub(_exp(result), temp, _exp(result));
592
593         /* mixed normal, subnormal values introduce an error of 1, correct it */
594         if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
595                 sc_val_from_ulong(1, temp);
596                 sc_add(_exp(result), temp, _exp(result));
597         }
598
599         sc_mul(_mant(a), _mant(b), _mant(result));
600
601         /* realign result: after a multiplication the digits right of the radix
602          * point are the sum of the factors' digits after the radix point. As all
603          * values are normalized they both have the same amount of these digits,
604          * which has to be restored by proper shifting
605          * because of the rounding bits */
606         sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
607
608         _shift_right(_mant(result), temp, _mant(result));
609         sticky = sc_had_carry();
610         fc_exact &= !sticky;
611
612         fc_exact &= normalize(result, result, sticky);
613 }
614
615 /**
616  * calculate a / b
617  */
618 static void _fdiv(const fp_value *a, const fp_value *b, fp_value *result) {
619         int sticky;
620         char *temp, *dividend;
621         char res_sign;
622
623         fc_exact = 1;
624
625         handle_NAN(a, b, result);
626
627         temp = alloca(value_size);
628         dividend = alloca(value_size);
629
630         if (result != a && result != b)
631                 result->desc = a->desc;
632
633         result->sign = res_sign = a->sign ^ b->sign;
634
635         /* produce NAN on 0/0 and inf/inf */
636         if (a->desc.clss == ZERO) {
637                 if (b->desc.clss == ZERO) {
638                         /* 0/0 -> NaN */
639                         fc_get_qnan(&a->desc, result);
640                         fc_exact = 0;
641                 } else {
642                         /* 0/x -> a */
643                         if (a != result)
644                                 memcpy(result, a, calc_buffer_size);
645                         result->sign = res_sign;
646                 }
647                 return;
648         }
649
650         if (b->desc.clss == INF) {
651                 fc_exact = 0;
652                 if (a->desc.clss == INF) {
653                         /* inf/inf -> NaN */
654                         fc_get_qnan(&a->desc, result);
655                 } else {
656                         /* x/inf -> 0 */
657                         sc_val_from_ulong(0, NULL);
658                         _save_result(_exp(result));
659                         _save_result(_mant(result));
660                         result->desc.clss = ZERO;
661                 }
662                 return;
663         }
664
665         if (a->desc.clss == INF) {
666                 fc_exact = 0;
667                 /* inf/x -> inf */
668                 if (a != result)
669                         memcpy(result, a, calc_buffer_size);
670                 result->sign = res_sign;
671                 return;
672         }
673         if (b->desc.clss == ZERO) {
674                 fc_exact = 0;
675                 /* division by zero */
676                 if (result->sign)
677                         fc_get_minusinf(&a->desc, result);
678                 else
679                         fc_get_plusinf(&a->desc, result);
680                 return;
681         }
682
683         /* exp = exp(a) - exp(b) + excess - 1*/
684         sc_sub(_exp(a), _exp(b), _exp(result));
685         sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 2, temp);
686         sc_add(_exp(result), temp, _exp(result));
687
688         /* mixed normal, subnormal values introduce an error of 1, correct it */
689         if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
690                 sc_val_from_ulong(1, temp);
691                 sc_add(_exp(result), temp, _exp(result));
692         }
693
694         /* mant(res) = mant(a) / 1/2mant(b) */
695         /* to gain more bits of precision in the result the dividend could be
696          * shifted left, as this operation does not loose bits. This would not
697          * fit into the integer precision, but due to the rounding bits (which
698          * are always zero because the values are all normalized) the divisor
699          * can be shifted right instead to achieve the same result */
700         sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
701
702         _shift_left(_mant(a), temp, dividend);
703
704         {
705                 char *divisor = alloca(calc_buffer_size);
706                 sc_val_from_ulong(1, divisor);
707                 _shift_right(_mant(b), divisor, divisor);
708                 sc_div(dividend, divisor, _mant(result));
709                 sticky = sc_had_carry();
710                 fc_exact &= !sticky;
711         }
712
713         fc_exact &= normalize(result, result, sticky);
714 }
715
716 #if 0
717 static void _power_of_ten(int exp, ieee_descriptor_t *desc, char *result) {
718         char *build;
719         char *temp;
720
721         /* positive sign */
722         result->sign = 0;
723
724         /* set new descriptor (else result is supposed to already have one) */
725         if (desc != NULL)
726                 result->desc = *desc;
727
728         build = alloca(value_size);
729         temp = alloca(value_size);
730
731         sc_val_from_ulong((1 << (result->desc.exponent_size - 1)) - 1, _exp(result));
732
733         if (exp > 0) {
734                 /* temp is value of ten now */
735                 sc_val_from_ulong(10, NULL);
736                 _save_result(temp);
737
738                 for (exp--; exp > 0; exp--) {
739                         _save_result(build);
740                         sc_mul(build, temp, NULL);
741                 }
742                 _save_result(build);
743
744                 /* temp is amount of left shift needed to put the value left of the radix point */
745                 sc_val_from_ulong(result->desc.mantissa_size + ROUNDING_BITS, temp);
746
747                 _shift_left(build, temp, _mant(result));
748
749                 _normalize(result, result, 0);
750         }
751 }
752 #endif
753
754 /**
755  * Truncate the fractional part away.
756  *
757  * This does not clip to any integer range.
758  */
759 static void _trunc(const fp_value *a, fp_value *result) {
760         /*
761          * When exponent == 0 all bits left of the radix point
762          * are the integral part of the value. For 15bit exp_size
763          * this would require a left shift of max. 16383 bits which
764          * is too much.
765          * But it is enough to ensure that no bit right of the radix
766          * point remains set. This restricts the interesting
767          * exponents to the interval [0, mant_size-1].
768          * Outside this interval the truncated value is either 0 or
769          * it does not have fractional parts.
770          */
771
772         int exp_bias, exp_val;
773         char *temp;
774
775         /* fixme: can be exact */
776         fc_exact = 0;
777
778         temp = alloca(value_size);
779
780         if (a != result)
781                 result->desc = a->desc;
782
783         exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
784         exp_val  = sc_val_to_long(_exp(a)) - exp_bias;
785
786         if (exp_val < 0) {
787                 sc_val_from_ulong(0, NULL);
788                 _save_result(_exp(result));
789                 _save_result(_mant(result));
790                 result->desc.clss = ZERO;
791
792                 return;
793         }
794
795         if (exp_val > a->desc.mantissa_size) {
796                 if (a != result)
797                         memcpy(result, a, calc_buffer_size);
798
799                 return;
800         }
801
802         /* set up a proper mask to delete all bits right of the
803          * radix point if the mantissa had been shifted until exp == 0 */
804         sc_max_from_bits(1 + exp_val, 0, temp);
805         sc_val_from_long(a->desc.mantissa_size - exp_val + 2, NULL);
806         _shift_left(temp, sc_get_buffer(), temp);
807
808         /* and the mask and return the result */
809         sc_and(_mant(a), temp, _mant(result));
810
811         if (a != result) {
812                 memcpy(_exp(result), _exp(a), value_size);
813                 result->sign = a->sign;
814         }
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 #if defined(HAVE_LONG_DOUBLE) && !defined(__CYGWIN__)
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         else if(value->desc.clss == INF) {
1229                 if (value->sign == 0)
1230                         return fc_get_plusinf(desc, result);
1231                 else
1232                         return fc_get_minusinf(desc, result);
1233         }
1234
1235         /* set the descriptor of the new value */
1236         result->desc.exponent_size = desc->exponent_size;
1237         result->desc.mantissa_size = desc->mantissa_size;
1238         result->desc.explicit_one  = desc->explicit_one;
1239         result->desc.clss          = value->desc.clss;
1240
1241         result->sign = value->sign;
1242
1243         /* when the mantissa sizes differ normalizing has to shift to align it.
1244          * this would change the exponent, which is unwanted. So calculate this
1245          * offset and add it */
1246         val_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1247         res_bias = (1 << (desc->exponent_size - 1)) - 1;
1248
1249         exp_offset = (res_bias - val_bias) - (value->desc.mantissa_size - desc->mantissa_size);
1250         sc_val_from_long(exp_offset, temp);
1251         sc_add(_exp(value), temp, _exp(result));
1252
1253         /* _normalize expects normalized radix point */
1254         if (value->desc.clss == SUBNORMAL) {
1255                 sc_val_from_ulong(1, NULL);
1256                 _shift_left(_mant(value), sc_get_buffer(), _mant(result));
1257         } else if (value != result) {
1258                 memcpy(_mant(result), _mant(value), value_size);
1259         } else {
1260                 memmove(_mant(result), _mant(value), value_size);
1261         }
1262
1263         normalize(result, result, 0);
1264         TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1265         return result;
1266 }
1267
1268 fp_value *fc_get_max(const ieee_descriptor_t *desc, fp_value *result) {
1269         if (result == NULL) result = calc_buffer;
1270
1271         result->desc.exponent_size = desc->exponent_size;
1272         result->desc.mantissa_size = desc->mantissa_size;
1273         result->desc.explicit_one  = desc->explicit_one;
1274         result->desc.clss          = NORMAL;
1275
1276         result->sign = 0;
1277
1278         sc_val_from_ulong((1 << desc->exponent_size) - 2, _exp(result));
1279
1280         sc_max_from_bits(desc->mantissa_size + 1, 0, _mant(result));
1281         sc_val_from_ulong(ROUNDING_BITS, NULL);
1282         _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1283
1284         return result;
1285 }
1286
1287 fp_value *fc_get_min(const ieee_descriptor_t *desc, fp_value *result) {
1288         if (result == NULL) result = calc_buffer;
1289
1290         fc_get_max(desc, result);
1291         result->sign = 1;
1292
1293         return result;
1294 }
1295
1296 fp_value *fc_get_snan(const ieee_descriptor_t *desc, fp_value *result) {
1297         if (result == NULL) result = calc_buffer;
1298
1299         result->desc.exponent_size = desc->exponent_size;
1300         result->desc.mantissa_size = desc->mantissa_size;
1301         result->desc.explicit_one  = desc->explicit_one;
1302         result->desc.clss          = NAN;
1303
1304         result->sign = 0;
1305
1306         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1307
1308         /* signaling NaN has non-zero mantissa with msb not set */
1309         sc_val_from_ulong(1, _mant(result));
1310
1311         return result;
1312 }
1313
1314 fp_value *fc_get_qnan(const ieee_descriptor_t *desc, fp_value *result) {
1315         if (result == NULL) result = calc_buffer;
1316
1317         result->desc.exponent_size = desc->exponent_size;
1318         result->desc.mantissa_size = desc->mantissa_size;
1319         result->desc.explicit_one  = desc->explicit_one;
1320         result->desc.clss          = NAN;
1321
1322         result->sign = 0;
1323
1324         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1325
1326         /* quiet NaN has the msb of the mantissa set, so shift one there */
1327         sc_val_from_ulong(1, _mant(result));
1328         /* mantissa_size >+< 1 because of two extra rounding bits */
1329         sc_val_from_ulong(desc->mantissa_size + 1, NULL);
1330         _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1331
1332         return result;
1333 }
1334
1335 fp_value *fc_get_plusinf(const ieee_descriptor_t *desc, fp_value *result)
1336 {
1337         char *mant;
1338
1339         if (result == NULL) result = calc_buffer;
1340
1341         result->desc.exponent_size = desc->exponent_size;
1342         result->desc.mantissa_size = desc->mantissa_size;
1343         result->desc.explicit_one  = desc->explicit_one;
1344         result->desc.clss          = INF;
1345
1346         result->sign = 0;
1347
1348         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1349
1350         mant = _mant(result);
1351         sc_val_from_ulong(0, mant);
1352         if (desc->explicit_one) {
1353                 sc_set_bit_at(mant, result->desc.mantissa_size + ROUNDING_BITS);
1354         }
1355
1356         return result;
1357 }
1358
1359 fp_value *fc_get_minusinf(const ieee_descriptor_t *desc, fp_value *result) {
1360         if (result == NULL) result = calc_buffer;
1361
1362         fc_get_plusinf(desc, result);
1363         result->sign = 1;
1364
1365         return result;
1366 }
1367
1368 int fc_comp(const fp_value *val_a, const fp_value *val_b) {
1369         int mul = 1;
1370
1371         /*
1372          * shortcut: if both values are identical, they are either
1373          * Unordered if NaN or equal
1374          */
1375         if (val_a == val_b)
1376                 return val_a->desc.clss == NAN ? 2 : 0;
1377
1378         /* unordered if one is a NaN */
1379         if (val_a->desc.clss == NAN || val_b->desc.clss == NAN)
1380                 return 2;
1381
1382         /* zero is equal independent of sign */
1383         if ((val_a->desc.clss == ZERO) && (val_b->desc.clss == ZERO))
1384                 return 0;
1385
1386         /* different signs make compare easy */
1387         if (val_a->sign != val_b->sign)
1388                 return (val_a->sign == 0) ? (1) : (-1);
1389
1390         mul = val_a->sign ? -1 : 1;
1391
1392         /* both infinity means equality */
1393         if ((val_a->desc.clss == INF) && (val_b->desc.clss == INF))
1394                 return 0;
1395
1396         /* infinity is bigger than the rest */
1397         if (val_a->desc.clss == INF)
1398                 return  1 * mul;
1399         if (val_b->desc.clss == INF)
1400                 return -1 * mul;
1401
1402         /* check first exponent, that mantissa if equal */
1403         switch (sc_comp(_exp(val_a), _exp(val_b))) {
1404         case -1:
1405                 return -1 * mul;
1406         case  1:
1407                 return  1 * mul;
1408         case  0:
1409                 return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1410         default:
1411                 return 2;
1412         }
1413 }
1414
1415 int fc_is_zero(const fp_value *a) {
1416         return a->desc.clss == ZERO;
1417 }
1418
1419 int fc_is_negative(const fp_value *a) {
1420         return a->sign;
1421 }
1422
1423 int fc_is_inf(const fp_value *a) {
1424         return a->desc.clss == INF;
1425 }
1426
1427 int fc_is_nan(const fp_value *a) {
1428         return a->desc.clss == NAN;
1429 }
1430
1431 int fc_is_subnormal(const fp_value *a) {
1432         return a->desc.clss == SUBNORMAL;
1433 }
1434
1435 char *fc_print(const fp_value *val, char *buf, int buflen, unsigned base) {
1436         char *mul_1;
1437         LLDBL flt_val;
1438
1439         mul_1 = alloca(calc_buffer_size);
1440
1441         switch (base) {
1442         case FC_DEC:
1443                 switch ((value_class_t)val->desc.clss) {
1444                 case INF:
1445                         snprintf(buf, buflen, "%cINF", val->sign ? '-' : '+');
1446                         break;
1447                 case NAN:
1448                         snprintf(buf, buflen, "NaN");
1449                         break;
1450                 case ZERO:
1451                         snprintf(buf, buflen, "0.0");
1452                         break;
1453                 default:
1454                         flt_val = fc_val_to_ieee754(val);
1455 #ifdef HAVE_LONG_DOUBLE
1456                         /* XXX 30 is arbitrary */
1457                         snprintf(buf, buflen, "%.30LE", flt_val);
1458 #else
1459                         snprintf(buf, buflen, "%.18E", flt_val);
1460 #endif
1461                 }
1462                 break;
1463
1464         case FC_HEX:
1465                 switch ((value_class_t)val->desc.clss) {
1466                 case INF:
1467                         snprintf(buf, buflen, "%cINF", val->sign ? '-' : '+');
1468                         break;
1469                 case NAN:
1470                         snprintf(buf, buflen, "NAN");
1471                         break;
1472                 case ZERO:
1473                         snprintf(buf, buflen, "0.0");
1474                         break;
1475                 default:
1476                         flt_val = fc_val_to_ieee754(val);
1477 #ifdef HAVE_LONG_DOUBLE
1478                         snprintf(buf, buflen, "%LA", flt_val);
1479 #else
1480                         snprintf(buf, buflen, "%A", flt_val);
1481 #endif
1482                 }
1483                 break;
1484
1485         case FC_PACKED:
1486         default:
1487                 snprintf(buf, buflen, "%s", sc_print(pack(val, mul_1), value_size*4, SC_HEX, 0));
1488                 buf[buflen - 1] = '\0';
1489                 break;
1490         }
1491         return buf;
1492 }
1493
1494 unsigned char fc_sub_bits(const fp_value *value, unsigned num_bits, unsigned byte_ofs) {
1495         /* this is used to cache the packed version of the value */
1496         static char *packed_value = NULL;
1497
1498         if (packed_value == NULL) packed_value = XMALLOCN(char, value_size);
1499
1500         if (value != NULL)
1501                 pack(value, packed_value);
1502
1503         return sc_sub_bits(packed_value, num_bits, byte_ofs);
1504 }
1505
1506 /* Returns non-zero if the mantissa is zero, i.e. 1.0Exxx */
1507 int fc_zero_mantissa(const fp_value *value) {
1508         return sc_get_lowest_set_bit(_mant(value)) == ROUNDING_BITS + value->desc.mantissa_size;
1509 }
1510
1511 /* Returns the exponent of a value. */
1512 int fc_get_exponent(const fp_value *value) {
1513         int exp_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1514         return sc_val_to_long(_exp(value)) - exp_bias;
1515 }
1516
1517 /* Return non-zero if a given value can be converted lossless into another precision */
1518 int fc_can_lossless_conv_to(const fp_value *value, const ieee_descriptor_t *desc) {
1519         int v;
1520         int exp_bias;
1521
1522         /* handle some special cases first */
1523         switch (value->desc.clss) {
1524         case ZERO:
1525         case INF:
1526         case NAN:
1527                 return 1;
1528         default:
1529                 break;
1530         }
1531
1532         /* check if the exponent can be encoded: note, 0 and all ones are reserved for the exponent */
1533         exp_bias = (1 << (desc->exponent_size - 1)) - 1;
1534         v = fc_get_exponent(value) + exp_bias;
1535         if (0 < v && v < (1 << desc->exponent_size) - 1) {
1536                 /* exponent can be encoded, now check the mantissa */
1537                 v = value->desc.mantissa_size + ROUNDING_BITS - sc_get_lowest_set_bit(_mant(value));
1538                 return v <= desc->mantissa_size;
1539         }
1540         return 0;
1541 }
1542
1543
1544 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode) {
1545         if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1546                 rounding_mode = mode;
1547
1548         return rounding_mode;
1549 }
1550
1551 fc_rounding_mode_t fc_get_rounding_mode(void) {
1552         return rounding_mode;
1553 }
1554
1555 void init_fltcalc(int precision) {
1556         if (calc_buffer == NULL) {
1557                 /* does nothing if already init */
1558                 if (precision == 0) precision = FC_DEFAULT_PRECISION;
1559
1560                 init_strcalc(precision + 2 + ROUNDING_BITS);
1561
1562                 /* needs additionally rounding bits, one bit as explicit 1., and one for
1563                  * addition overflow */
1564                 max_precision = sc_get_precision() - (2 + ROUNDING_BITS);
1565                 if (max_precision < precision)
1566                         printf("WARNING: not enough precision available, using %d\n", max_precision);
1567
1568                 rounding_mode    = FC_TONEAREST;
1569                 value_size       = sc_get_buffer_length();
1570                 calc_buffer_size = sizeof(fp_value) + 2*value_size - 1;
1571
1572                 calc_buffer = xmalloc(calc_buffer_size);
1573                 memset(calc_buffer, 0, calc_buffer_size);
1574                 DEBUGPRINTF(("init fltcalc:\n\tVALUE_SIZE = %d\ntCALC_BUFFER_SIZE = %d\n\tcalc_buffer = %p\n\n", value_size, calc_buffer_size, calc_buffer));
1575 #ifdef HAVE_LONG_DOUBLE
1576                 DEBUGPRINTF(("\tUsing long double (1-15-64) interface\n"));
1577 #else
1578                 DEBUGPRINTF(("\tUsing double (1-11-52) interface\n"));
1579 #endif
1580 #ifdef WORDS_BIGENDIAN
1581                 DEBUGPRINTF(("\tWord order is big endian\n\n"));
1582 #else
1583                 DEBUGPRINTF(("\tWord order is little endian\n\n"));
1584 #endif
1585         }
1586 }
1587
1588 void finish_fltcalc (void) {
1589         free(calc_buffer); calc_buffer = NULL;
1590 }
1591
1592 #ifdef FLTCALC_TRACE_CALC
1593 static char buffer[100];
1594 #endif
1595
1596 /* definition of interface functions */
1597 fp_value *fc_add(const fp_value *a, const fp_value *b, fp_value *result) {
1598         if (result == NULL) result = calc_buffer;
1599
1600         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1601         TRACEPRINTF(("+ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1602
1603         /* make the value with the bigger exponent the first one */
1604         if (sc_comp(_exp(a), _exp(b)) == -1)
1605                 _fadd(b, a, result);
1606         else
1607                 _fadd(a, b, result);
1608
1609         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1610         return result;
1611 }
1612
1613 fp_value *fc_sub(const fp_value *a, const fp_value *b, fp_value *result) {
1614         fp_value *temp;
1615
1616         if (result == NULL) result = calc_buffer;
1617
1618         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1619         TRACEPRINTF(("- %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1620
1621         temp = alloca(calc_buffer_size);
1622         memcpy(temp, b, calc_buffer_size);
1623         temp->sign = !b->sign;
1624         if (sc_comp(_exp(a), _exp(temp)) == -1)
1625                 _fadd(temp, a, result);
1626         else
1627                 _fadd(a, temp, result);
1628
1629         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1630         return result;
1631 }
1632
1633 fp_value *fc_mul(const fp_value *a, const fp_value *b, fp_value *result) {
1634         if (result == NULL) result = calc_buffer;
1635
1636         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1637         TRACEPRINTF(("* %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1638
1639         _fmul(a, b, result);
1640
1641         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1642         return result;
1643 }
1644
1645 fp_value *fc_div(const fp_value *a, const fp_value *b, fp_value *result) {
1646         if (result == NULL) result = calc_buffer;
1647
1648         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1649         TRACEPRINTF(("/ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1650
1651         _fdiv(a, b, result);
1652
1653         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1654         return result;
1655 }
1656
1657 fp_value *fc_neg(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
1662         if (a != result)
1663                 memcpy(result, a, calc_buffer_size);
1664         result->sign = !a->sign;
1665
1666         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1667         return result;
1668 }
1669
1670 fp_value *fc_int(const fp_value *a, fp_value *result) {
1671         if (result == NULL) result = calc_buffer;
1672
1673         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1674         TRACEPRINTF(("truncated to integer "));
1675
1676         _trunc(a, result);
1677
1678         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1679         return result;
1680 }
1681
1682 fp_value *fc_rnd(const fp_value *a, fp_value *result) {
1683         if (result == NULL) result = calc_buffer;
1684
1685         (void) a;
1686         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1687         TRACEPRINTF(("rounded to integer "));
1688
1689         assert(!"fc_rnd() not yet implemented");
1690
1691         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1692         return result;
1693 }
1694
1695 /*
1696  * convert a floating point value into an sc value ...
1697  */
1698 int fc_flt2int(const fp_value *a, void *result, ir_mode *dst_mode)
1699 {
1700         if (a->desc.clss == NORMAL) {
1701                 int exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
1702                 int exp_val  = sc_val_to_long(_exp(a)) - exp_bias;
1703                 int shift, highest;
1704                 int mantissa_size;
1705                 int tgt_bits;
1706
1707                 if (a->sign && !mode_is_signed(dst_mode)) {
1708                         /* FIXME: for now we cannot convert this */
1709                         return 0;
1710                 }
1711
1712                 tgt_bits = get_mode_size_bits(dst_mode);
1713                 if (mode_is_signed(dst_mode))
1714                         --tgt_bits;
1715
1716                 assert(exp_val >= 0 && "floating point value not integral before fc_flt2int() call");
1717                 mantissa_size = a->desc.mantissa_size + ROUNDING_BITS;
1718                 shift         = exp_val - mantissa_size;
1719
1720                 if (tgt_bits < mantissa_size + 1)
1721                         tgt_bits = mantissa_size + 1;
1722                 if (shift > 0) {
1723                         sc_shlI(_mant(a),  shift, tgt_bits, 0, result);
1724                 } else {
1725                         sc_shrI(_mant(a), -shift, tgt_bits, 0, result);
1726                 }
1727
1728                 /* check for overflow */
1729                 highest = sc_get_highest_set_bit(result);
1730
1731                 if (mode_is_signed(dst_mode)) {
1732                         if (highest == sc_get_lowest_set_bit(result)) {
1733                                 /* need extra test for MIN_INT */
1734                                 if (highest >= (int) get_mode_size_bits(dst_mode)) {
1735                                         /* FIXME: handle overflow */
1736                                         return 0;
1737                                 }
1738                         } else {
1739                                 if (highest >= (int) get_mode_size_bits(dst_mode) - 1) {
1740                                         /* FIXME: handle overflow */
1741                                         return 0;
1742                                 }
1743                         }
1744                 } else {
1745                         if (highest >= (int) get_mode_size_bits(dst_mode)) {
1746                                 /* FIXME: handle overflow */
1747                                 return 0;
1748                         }
1749                 }
1750
1751                 if (a->sign)
1752                         sc_neg(result, result);
1753
1754                 return 1;
1755         }
1756         else if (a->desc.clss == ZERO) {
1757                 sc_zero(result);
1758                 return 1;
1759         }
1760         return 0;
1761 }
1762
1763
1764 unsigned fc_set_immediate_precision(unsigned bits) {
1765         unsigned old = immediate_prec;
1766
1767         immediate_prec = bits;
1768         return old;
1769 }
1770
1771 int fc_is_exact(void) {
1772         return fc_exact;
1773 }