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