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