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